对象浅拷贝
1、 Object.assign()
var obj = {
name: 'zhang',
info: {
age: 10,
},
grade: [10, 20]
}
var copyObj = Object.assign({}, obj)
2、es6 展开运算符...
var obj = {
name: 'zhang',
info: {
age: 10,
},
grade: [10, 20]
}
var copyObj = { ... obj }
数组浅拷贝
1、Array.slice() 数组截取,返回新的数组
var arr = [10, {age: 1, info: {name: 'zhangsan'}}]
var copyArr = arr.slice()
2、Array.concat() 数组合并
var arr = [10, {age: 1, info: {name: 'zhangsan'}}]
var copyArr = arr.concat([], arr)
3、es6 展开运算符...
var arr = [10, {age: 1, info: {name: 'zhangsan'}}]
var copyArr = [...arr]
递归实现对象深拷贝
拷贝的时候判断一下属性值的类型,如果是对象,我们递归调用深拷贝函数
var obj = {
name: 'zhang',
info: {
age: 10,
},
grade: [10, 20]
}
var deepCopy = function(obj) {
if (typeof obj !== 'object') return;
var newObj = obj instanceof Array ? [] : {};
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
newObj[key] = typeof obj[key] === 'object' ? deepCopy(obj[key]) : obj[key];
}
}
return newObj;
}
网友评论