这里可以不用 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
截取字符串意义不大,画蛇添足
00 -
双越
2021-06-04
这样也可以。但用 instanceOf 会更加方便,代码更加简洁。
00
相似问题