解构
数组:
const [a, b, c, d = 4] = [1, 2, 3]
console.log(a, b, c, d) // 1 2 3 4
const [a, b, [c, d]] = [1, 2, [3, 4]]
console.log(a, b, c, d) // 1 2 3 4
对象:
const user = {name: 'zhangsan',age: 10
}
let { age: uage, name: uname } = user // 别名
let { age, name } = user
字符串:
let [a, b, c, d] = 'love'
console.log(a, b, c, d) // l o v e
参数:
function foo([a, b, c]) {console.log(a, b, c) // 1 2 3
}
foo([1, 2, 3])function foo2({ name, age = 18 }) {console.log(name, age) // zs 18
}
foo2({name: 'zs'
})
rest
解构
function foo(a, b, c) {console.log(a, b, c) // 1 2 3
}
const arr = [1, 2, 3]
foo(...arr)
const str = 'zs'
const arr = [...str] // [ 'z', 's' ]
合并
const obj = { ...obj1, ...obj2 }
const arr = [...arr1, ...arr2]
arr1.push(...arr2)
剩余参数
function foo(x, ...args) {console.log(x) // 1console.log(args) // [ 2, 3, 4 ]
}
foo(1, 2, 3, 4)
const obj4 = {name: 'zhangsan',age: 18,school: '清华大学',id: '001'
}
const { name, age, ...rest } = obj4
深拷贝
const obj1 = {name: 'zhangsan',age: 34
}
const obj2 = {...obj1
}
obj1.name = 'lisi'
console.log(obj1) // {name: 'lisi', age: 34}
console.log(obj2) // {name: 'zhangsan', age: 34}