深色模式
浅拷贝和深拷贝
浅拷贝
js
function clone(target) {
if (typeof target !== 'object') return target;
const newObject = {};
for (var key in target) newObject[key] = target[key];
return newObject;
}
深拷贝
js
function deepClone(target) {
if (!(target instanceof Object)) return target;
if (Array.isArray(target)) {
let res = [];
target.forEach((item) => {
res.push(deepClone(item));
});
return res;
}
const newObject = {};
for (let key in target) {
let value = target[key];
if (typeof value === 'function') {
newObject[key] = value.bind(newObject);
} else if (typeof value === 'object') {
if (Array.isArray(value)) {
newObject[key] = [];
value.forEach((item) => {
newObject[key].push(deepClone(item));
});
} else {
newObject[key] = deepClone(value);
}
}
}
return newObject;
}