ES2018 为对象解构提供 rest 参数和spread扩展运算符。
1. 合并俩对象:
let obj = {a:1,b:2}, obj2={} let obj3 = {...obj, ...obj2} console.log(obj3) // {a: 1, b: 2}
2. 对象的值如果是undefined 或者 null
let obj1 = {a: 1, b: 2}, obj2={c: undefined, d: null} console.log({...obj1, ...obj2}) //{a: 1, b: 2, c: undefined, d: null}
3. 对象的属性是不可枚举的:
let obj1 = Object.defineProperty({}, ‘f‘, {value: 1}) //defineProperty 枚举属性默认为false let obj2 = {g: 2} console.log({...obj1, ...obj2})// {g: 2} 不复制不可枚举的属性 console.log(Object.assign(obj1, obj2)) //{g: 2, f: 1}
题外话:如何判断一个对象的某个属性是否可枚举...啊,还是甩链接吧...
属性的可枚举性和所有权
4. spread 是浅拷贝:这意味着在多维数组、嵌套对象中会出问题:
//先看数组: 官网的例子 var a = [[1], [2], [3]]; var b = [...a]; b.shift().shift() console.log(a) //[[], [2], [3]] console.log(b) //[[2], [3]] //再看对象: let o1 = {a:{aa: 1}, b:{bb: 2}} let o2 = {...o1} o2.a.aa=3 console.log(o2) // {a: {aa: 3}, b: {bb: 2}} console.log(o1) // {a: {aa: 3}, b: {bb: 2}} 克隆对象o2的a属性值,指向o1.a。o2.b = 4
console.log(o2) // {a: {aa: 3}, b: 4} console.log(o1) // {a: {aa: 3}, b: {bb: 2}}
let obj2 = {g: 2} let obj3 = {...obj2} obj3.g = 4 console.log(obj2) //{g: 2}
对于prototype还是说不出个所以然...先这样..
原文地址:https://www.cnblogs.com/dodocie/p/9494485.html
时间: 2024-11-06 07:41:44