文章目录
- 浅拷贝
- 简单深拷贝
浅拷贝
const _shallowClone = target => {let copy = Array.isArray(target) ? [] : {};for (let key in target) {if (target.hasOwnProperty(key)) {let value = target[key];copy[key] = value;}}return copy;
};
在这段代码中,我们定义了 _shallowClone 函数,它接受一个参数 target,表示要进行浅拷贝的目标对象。
首先,我们根据 target 的类型创建一个空的副本对象 copy。如果 target 是数组,则创建一个空数组作为
copy;否则,创建一个空对象。然后,我们使用 for…in 循环遍历 target 对象的属性。对于每个属性,我们将其值赋给 value 变量,并将其复制到 copy
对象中的相应键名位置。请注意,为了确保只拷贝 target 自身的属性,我们使用了 hasOwnProperty 方法进行检查。
最后,我们返回拷贝后的 copy 对象。
简单深拷贝
const _sampleDeepClone = target => {if (typeof target !== 'object' || target === null) {return target;}const cloneTarget = Array.isArray(target) ? [] : {};for (let key in target) {if (target.hasOwnProperty(key)) {if (target[key] && typeof target[key] === 'object') {cloneTarget[key] = _sampleDeepClone(target[key]);} else {cloneTarget[key] = target[key];}}}return cloneTarget;
};
在这段代码中,我们定义了 _sampleDeepClone 函数,它接受一个参数 target,表示要进行简单深拷贝的目标对象。
首先,我们对 target 进行类型判断。如果 target 的类型不是对象或为 null,则直接返回 target,因为不需要进行拷贝。
然后,我们根据 target 的类型创建一个空的克隆对象 cloneTarget。如果 target 是数组,则创建一个空数组作为
cloneTarget;否则,创建一个空对象。接下来,我们使用 for…in 循环遍历 target 对象的属性。对于每个属性,我们首先使用 hasOwnProperty
方法进行检查,确保只拷贝 target 自身的属性。然后,我们判断当前属性值 target[key] 的类型。如果它是对象且不为 null,则递归调用 _sampleDeepClone
函数进行深拷贝,并将拷贝后的结果赋值给 cloneTarget[key]。否则,直接将属性值复制到 cloneTarget[key]。最后,我们返回完成深拷贝的 cloneTarget 对象。