chdyiboke / weekly

issue and share weekly
5 stars 1 forks source link

解构赋值对object类型只是浅拷贝,扩展运算符同样 #33

Open chdyiboke opened 4 years ago

chdyiboke commented 4 years ago

修改值后会不会影响原变量???会影响就是浅拷贝

chdyiboke commented 4 years ago

const a = { name: 'name', age: 18, marriage: false, addr: { province: 'sichuan', city: 'chengdu' } }

let { name, age, marriage, addr } = a

name = 'myname' age = 26 marriage = true addr.province = 'shanghai' addr.city = 'shanghai'

console.log(name, age, marriage, addr) console.log(a)

chdyiboke commented 4 years ago

// myname 26 true {province: "shanghai", city: "shanghai"} // { name: "name", age: 18, marriage: false, addr: {province: "shanghai", city: "shanghai"} }

chdyiboke commented 4 years ago

object类型 是浅拷贝,addr 值被修改了。

chdyiboke commented 4 years ago

扩展运算符:拷贝一层,也是浅拷贝。

let a = [1,2,3]; let b = [...a]; a == b // false

but ========》》》》》》》》》》》

let a = [1,2,[1,2,3]]; let b = [...a]; a[2][1] = 11; console.log(a); // [ 1, 2, [ 1, 11, 3 ] ] console.log(b); // [ 1, 2, [ 1, 11, 3 ] ]