浅拷贝,只能拷贝一层对象,针对对象的嵌套无法解决
- array.slice
var numbers = [1,2,3]
var new_numbers = numbers.slice();
- array.concat
var strings = ['a', 'b', 'c']
var new_strings = strings.concat();
- Object.assign
var person = {name: 'garen', age: 18};
var new_person = Object.assign({}, person);
- 展开运算符
var fruits = ['apple', 'banana', 'orange'];
var new_fruits = [...fruits];
- 自己实现shadowCopy
function shadowCopy(target) {
if(typeof target !== null && typeof target === 'object') {
let cloneTarget = Array.isArray(target) ? []: {};
for (let prop in target) {
if(target.hasOwnProperty(prop)) {
cloneTarget[prop] = target[prop]
}
}
return cloneTarget;
} else {
return target;
}
}