这里可以不用 instanceof

来源:2-2 typeof和深拷贝

vZina

2021-06-04

这里可以不用 instanceof 判定,用 toString 方法也成

let checkType = (target) => {
    // [object Object]
    // [object Array]
    return Object.prototype.toString.call(target).slice(8,-1) // 从第8位开始截取,倒数第2位结束
}

let deepClone = (target) => {
    let result;
    let type = checkType(target);
    if (type === 'Object') {
        result = {};
    } else if (type === 'Array') {
        result = [];
    } else {
        result = target;
    }
    for(let i in target){
        if(target.hasOwnProperty(i)){
            let value = target[i];
            if (checkType(value) === 'Object' || checkType(value) === 'Array') {
                deepClone(value);
            } else {
                result[i] = value;
            }
        }
    }
    return result;
}
写回答

2回答

慕粉547471488

2021-06-25

截取字符串意义不大,画蛇添足

0
0

双越

2021-06-04

这样也可以。但用 instanceOf 会更加方便,代码更加简洁。

0
0

BAT大牛带你横扫初级前端JavaScript面试(第二版)

BAT高级前端工程师亲授,结合真实面试题,提高面试成功几率

4268 学习 · 817 问题

查看课程