前端面试之JS手写深拷贝
其中 instanceof 和 hasOwnProperty 概念尤为重要
// 原对象
const oldObj = {
name: '沸羊羊',
age: 6,
colors: ['orange', 'green', 'blue'],
friend: {
name: '黑小虎',
},
};
function deepClone(obj = {}) {
if (typeof obj !== 'object' || obj == null) {
return obj;
}
let result;
// 判断数据类型后创建
if (obj instanceof Array) {
result = [];
} else {
result = {};
}
// 循环遍历 key 进行深拷贝
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
result[key] = deepClone(obj[key]);
}
}
return result;
}
const newObj = deepClone(oldObj);
newObj.name = '喜羊羊';
newObj.friend.name = '虹猫';
newObj.colors[0] = 'red';
console.log('oldObj', oldObj);
console.log('newObj', newObj);
相关链接
instanceof