对象解构
- 传默认值
let node = {
size: '2',
color: 'red'
}
let { size, color = 'blue', ab = 'true' } = node
console.log(size, color, ab) //2 red true
- 变量更名以及传默认值
let node = {
size: '2',
color: 'red'
}
let { size: size1, color: color1, ab: ab1 = true } = node
console.log(size1, color1, ab1) // 2 red true
- 访问嵌套对象
let node = {
type: 'node',
prototype: {
color: 'red',
size: 2
}
}
let { type, prototype: { color } } = node
console.log(type, color) //node red
所有冒号前面的标识符均为检索的位置, 后面如果是一个花括号,则表示被赋值的变量名称。
数组解构
- 获取值
let colors = ['red', 'green', 'blue']
let [first, seconde] = colors
console.log(first, seconde)//red green
let [,, thirdElement] = colors
console.log(thirdElement)//blue
- 传默认值
let colors = ['red', 'green', 'blue']
let [,,, four = 'yellow'] = colors
console.log(four)//yellow
- 嵌套数组
let colors = ['red', ['green', 'blue']]
let [, [two]] = colors
console.log(two) //green
- 不定元素获取使用…
let colors = ['red', 'green', 'blue']
let [first, ...remains] = colors
console.log(first)// red
console.log(remains)// [ 'green', 'blue' ]
函数参数的解构
试用场景: 函数参数不定时,又想在函数中清晰看到可能包含哪些参数,可将不定参数方法解构语法中。
function setCookie (name, value, { test1, test2, test3 }) {
console.log(name, value, test1)
}
setCookie(1, 2, { test1: 1 })// 1 2 1
传默认值:
function setCookie (name, value, { test1, test2 = true, test3 }) {
console.log(name, value, test1, test2)
}
setCookie(1, 2, { test1: 1 })// 1 2 1 true