ES6允许按照一定模式,从数组和对象中提取值,对变量进行赋值,这被称为解构
//以前的写法
let a=1;
let b=2;
let c=3;
//es6写法
let [a,b,c] = [1,2,3];
只要等号两边的模式相同,左边的变量就会被赋予对应的值。
数组的解构赋值
let [a,[[b],c]] = [1,[[2],3]];
let [ , , third] = [1,2,3];
third //3
如果解构不成功,变量的值就等于undefined。
解构赋值允许指定默认值。
let [foo = true] = [];
foo //true
对象的解构赋值
let {foo,bar} = {foo: "aaa",bar: "bbb"};
foo // "aaa"
bar // "bbb"
数组的元素是按照次序排列的,变量的值由位置决定。而对于对象,变量必须与属性同名才能取到正确的值。
字符串的解构赋值
const [a,b,c,d,e] = 'hello'
a //'h'
b //'e'
c //'l'
d //'l'
e //'o'
数值和布尔值的解构赋值
解构赋值时,如果等号右边是数值和布尔值则会转为对象。
let {toString: s} = 123;
s === Number.prototype.toString // true
let {toString: s} = true;
s === Boolean.prototype.toString // true
函数参数的解构赋值
function add([x,y]){
return x+y
}
add([1,2]) //3
//使用默认值
function move({x = 0, y = 0} = {}) {
return [x, y];
}
move({}); //[0,0]
解构赋值的用途
交换变量的值
let x = 1; ley y = 2; [x,y] = [y,x];
从函数返回多个值
function example() { return [1,2,3]; } let [a,b,c] = example();
函数参数的定义
function f([x,y,z]){...} f([1,2,3]);
提取json数据(常用)
let jsonData = { id: 42, status: "OK", data: [867, 5309] }; let {id,status} = jsonData;
函数参数的默认值(常用)
function (a=1,b=2){ return a+b; }
遍历Map结构
var map = new Map(); 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
输入模块的指定方法(常用)
const { SourceMapConsumer, SourceNode } = require("source-map");