Anthony的博客

要做编程里最会摄影的,摄影里最会编程的。

0%

数组对象解构赋值

数组对象解构赋值

对象

1
2
3
4
5
6
let node = {
type: 'Identifier',
name: 'foo'
};
let { type, name } = node;
console.log(type, name); // Identifier foo
1
2
3
4
5
let node = {
type: 'Identifier'
};
let { type, name = 'wozien' } = node;
console.log(type, name); // Identifier wozien
1
2
3
4
5
6
let node = {
type: 'Identifier',
name: 'foo'
};
let { type: myType, name: myName = 'wozien' } = node;
console.log(myType, myName); // Identifier foo

数组

1
2
3
let colors = ['red', 'green', 'blue'];
let [firstColor, secondColor] = colors;
console.log(firstColor, secondColor); // red green
1
2
3
let colors = ['red'];
let [firstColor, secondColor = 'green'] = colors;
console.log(firstColor, secondColor); //red green
1
2
3
4
let colors = ['red', 'green', 'blue'];
let [firstColor, ...secondColor] = colors;
console.log(firstColor); //red
console.log(secondColor); // [ 'green', 'blue' ]

应用场景

函数解构

1
2
3
4
5
function setCookie(name, value, { path, domain, expire }) {
// 设置cookie
console.log(path, domain); // /,localhost
}
setCookie('a', 'b', { path: '/', domain: 'localhost' });
1
2
3
4
5
function setCookie(name, value, { path, domain, expire } = {}) {
// 设置cookie
console.log(path, domain); // undefinded,undefinded
}
setCookie('a', 'b');
-------------本文结束感谢您的阅读-------------