解构
解构分为两中,一种为解,另外一种为构;通俗易懂的讲就是解包、打包
// 原始包
const obj = {
key1: 1,
key2: 2,
key3: 3,
}
// 解包
const { key1, key2, key3 } = obj
// 打包
const test = ({ ...rest }) => {
console.log('result', rest)
}
test({ key1, key2, key3 })
解包的情形及注意点
数组的解包,占位一一对应,超出则为undefined
let [a, [b], d] = [1, [2, 3], 4];
a // 1
b // 2
d // 4
对象的解包:
let { foo, bar } = { foo: 'aaa', bar: 'bbb' };
foo // "aaa"
bar // "bbb"
let { foo: fo, bar: ba } = { foo: 'aaa', bar: 'bbb' };
fo // "aaa"
ba // "bbb"
map的解包
const map = new Map(); // map结构存在iterator接口,因此可以for ...of
map.set('first', 'hello');
map.set('second', 'world');
for (let [key, value] of map) {
console.log(key + " is " + value);
}
// first is hello
// second is world
注意:圆括号的使用情形【当并不是声明变量,同时也进行解构赋值时】
用途
一、值得交换
let x = 1;
let y = 2;
[x, y] = [y, x];
二、传参
const test = ({ ...rest }) => {
console.log('result', rest)
}
test({ key1, key2, key3 })
三、取值【json/对象】
const delay = () => {
return {
key1: 1,
key2: 2,
key3: 3,
}
}
const { key1, key2, key3 } = delay()
四、函数默认值
const delay = () => {`在这里插入代码片`
return {
key1: 1,
key2: 2,
key3: 3,
}
}
const { key1 = 1, key2 = 2, key3 = 3 } = delay()
五、遍历map结构
const map = new Map()
map.set('first', 'value')
map.set('second', 'value')
for(const [key, value] of map) {
console.log('key', key)
console.log('value', value)
}