数组的拷贝 浅拷贝和深拷贝

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)

 

posted @ 2018-08-08 15:25  悔创阿里-杰克马  阅读(396)  评论(0编辑  收藏  举报
求投食~(点图即可)