题解 | #浅拷贝#两种思路实现
浅拷贝
https://www.nowcoder.com/practice/434d236e52994a9791a055f1f7adf985
const _shallowClone = target => {
if (typeof target !== 'object' || target === null) return;
return Object.assign({}, target);
};
const _shallowClone = obj => {
// 补全代码
if (typeof obj !== 'object' || obj === null) {
return obj;
}
// 创建一个新的对象
const newObj = {};
// 遍历原对象的属性并复制到新对象中
for (const key in obj) {
if (obj.hasOwnProperty(key)) { //确保只获取对象自身的属性,而不包括继承的属性。这个看需求
newObj[key] = obj[key];
}
}
return newObj;
}
两种思路实现

