1这些都是浅拷贝
Objec.assign([],obj)
Array.slice(0)
var data2 = data.concat(); var arr = [1,2,3,4,5] var [ ...arr2 ] = arr arr[2] = 5 console.log(arr) console.log(arr2)
运行结构如下:
2正确深拷贝姿势 for循环实现深拷贝
var obj = { name: 'FungLeo', sex: 'man', old: '18' } var obj2 = copyObj(obj) function copyObj(obj) { let res = {} for (var key in obj) { res[key] = obj[key] } return res }
var obj = { name: 'FungLeo', sex: 'man', old: '18' } var obj2 = JSON.parse(JSON.stringify(obj))
转换成json再转换成对象实现对象的深拷贝
扩展运算符实现对象的浅拷贝
var obj = { name: 'FungLeo', sex: 'man', old: '18' } var { ...obj2 } = obj obj.old = '22' console.log(obj) console.log(obj2)