一、解构赋值 按照一定模式 从数组、对象中获取值并赋给变量
let [a,b,c] = [1,2,3];
console.log(a+","+b+","+c);
let [head,...tail] = [1,2,3,4];
console.log(head+"-----"+tail);
let [x,y,...z] = ['a'];
console.log(x+"---"+y+"---"+z);
console.log(z.length);
解构不成功时 赋值为undefined
let [foo] = [];
不完全解构(等号左边仅匹配部分右边)情况下,解构依然成功
let [a,[b],d] = [1,[2,3],4];
console.log(a+","+b+","+d);
若等号右边不是数组,或不是可遍历的解构,将会报错 x is not iterable
let [foo] = 1;
let [foo] = false;
let [foo] = NaN;
let [foo] = undefined;
let [foo] = null;
let [foo] = {};
let [foo] = [];
console.log(foo);
解构赋值时允许指定默认值 只有在右侧数组成员 === undefined 时,默认值才会生效 null===undefiend ? false
let [foo = true] = [];
console.log(foo);
let [x, y = 'b'] = ['a', undefined];
console.log(x+","+y);
let [z = 1] = [null];
console.log(z);
如果默认值是一个表达式,那么这个表达式是惰性求值的,只有在用到的时候才会求值
function f() {
console.log('aaa');
}
let [x = f()] = [1];
默认值可以引用解构赋值其他变量,但使用时该变量必须已经声明 否则报错x is not defined
let[x = 1,y = x] = [];
let[z=1,k=z] = [2];
let[a = b,b = 2] = [];
二、对象的解构赋值 数组的解构赋值按照元素位置一一对应,对象属性是无序的,需要变量与属性名同名,才能取到正确值
let { bar, foo } = { foo: "aaa", bar: "bbb" };
console.log(bar+","+foo);
let {baz} = {foo:"ccc"};
console.log(baz);
属性名是匹配的模式 属性值变量才是被赋值的
let { foo: baz } = { foo: "aaa", bar: "bbb" };
console.log(foo+","+baz);
嵌套赋值
let obj = {
p: [
'Hello',
{ y: 'World' }
]
};
let { p: [x, { y }] } = obj;
console.log(x+","+y);
指定默认值 对象属性值===undefined时生效
let {x: y = 3} = {}
console.log(y);
var {x: y = 3} = {x: 5};
console.log(y);
三、字符串解构赋值 字符串被转换成类数组对象,有length属性
const [a, b, c, d, e] = 'hello';
let {length : len} = 'hello'
四、数值、布尔值的解构赋值 先转换为对应的包装对象
let {toString: s} = 123;
console.log(s);
let { prop: x } = undefined; // Cannot destructure property `prop` of 'undefined' or 'null'
let { prop: y } = null;
console.log(x);
五、函数参数的解构赋值
function add([x, y]){
return x + y;
}
console.log(add([1, 2]));
函数参数解构使用默认值
function move({x = 0, y = 0} = {}) {
return [x, y];
}
move({x: 3, y: 8});
move({x: 3});
move({});
move();
function move({x, y} = { x: 0, y: 0 }) {
return [x, y];
}
move({x: 3, y: 8});
move({x: 3});
move({});
move();
可以使用圆括号的情况-----赋值语句的非模式部分
[(b)] = [3]; // 正确
({ p: (d) } = {}); // 正确
[(parseInt.prop)] = [3]; // 正确
六、解构赋值的用途
1.交换变量的值
let x =1;let y = 5;
[x,y] = [y,x];
console.log(x+"---"+y);
2.从函数返回多个值
// 返回一个数组
function example() {
return [1, 2, 3];
}
let [a, b, c] = example();
3.定义函数参数
function f([x, y, z]) {
return x+y+z;
}
f([1, 2, 3]);
4.提取JSON数据
let jsonData = {
id: 42,
status: "OK",
data: [867, 5309]
};
let { id, status, data: number } = jsonData;
console.log(id, status, number);
5.指定函数参数默认值
function add(x=0,y=1){
return x+y;
}
6.遍历Map结构
const map = new Map();
map.set('first', 'hello');
map.set('second', 'world');
for (let [key, value] of map) {
console.log(key + " is " + value);
}
7.输入模块的指定方法
const { SourceMapConsumer, SourceNode } = require("source-map");