// 使用递归来实现一个深度克隆,可以复制一个目标对象,返回一个完整拷贝
var deepClone = function fnDeepClone(obj){
var result = typeof obj.splice === 'function'?[]:{},//如果这句注释掉,会抛出异常,这句发挥的是什么作用?
key;
if (obj && typeof obj === 'object'){//这句怎么理解?如果obj是对象,typeof obj一定是对象啊。
for (key in obj ){
if (obj[key] && typeof obj[key] === 'object'){
result[key] = fnDeepClone(obj[key]);
}else{
result[key] = obj[key];//这句怎么理解?复制的不是值,而是键值对?
}
}
return result;
}
return obj;
}
var arr=[2,3,[6,7]];
var brr=deepClone(arr);
console.log(brr);
Determine whether the current obj is an object or an array. If it is an array, then result is also an array, otherwise result is an ordinary object
Your understanding is wrong, this sentence means如果 obj 存在,并且是对象
If it is not a reference type (object), it means that the value of the current key is a basic type, then directly set the key corresponding to the new result to this value
by the way. Because deep copying an object may cause memory leaks. Because key may refer to a type, thereby internally referencing itself and causing a memory leak, deep copy will only copy the address of the heap memory when encountering a reference type key.
And in the first line of the question, it is not rigorous to judge whether it is an array or an object by judging
splice
. What if there is a property called splice under the object that happens to be a function? The Array.isArray method has good support and can be replaced with this .For ES6, just
Object.assign()
justDetermine whether obj is an object or an array, because only arrays have the splice method. If
obj.splice
has a return value indicating that obj is an array, then the result is also an array, otherwise the result is an object.if (obj exists, and obj is an object), because null
typeof
is also an object, and one more step of judgment can remove null.If the copied value is a
private
值,那么就直接赋值就可以,如果是对象,那么就像上一步一样递归的复制对象,直到复制的值是private
value.Speaking of shallow copying and deep copying, I shamelessly recommend you to read an article I wrote...
/a/11...