一、数组的解构赋值
let [foo, [[bar], baz]] = [1, [[2], 3]];
①可多不可少,等号的右边是数组
let [x, y] = [1, 2, 3]; //可以 let [bar, foo] = [1]; //foo的值为undefined // 报错 let [foo] = 1; let [foo] = false; let [foo] = NaN; let [foo] = undefined; let [foo] = null; let [foo] = {}; //(具备 Iterator 接口?)
②默认值
let [foo = true] = []; foo // true
二、对象的解构赋值
①对象的属性没有次序,变量必须与属性同名,才能取到正确的值
let { foo, bar } = { foo: "aaa", bar: "bbb" }; foo // "aaa" bar // "bbb"
//(全)
let { foo: foo, bar: bar } = { foo: "aaa", bar: "bbb" };
②对象的解构赋值的内部机制,是先找到同名属性,然后再赋给对应的变量
//foo是匹配的模式,baz才是变量 let { foo: baz } = { foo: "aaa", bar: "bbb" }; baz // "aaa" foo // error: foo is not defined
③对数组进行对象解构
let arr = [1, 2, 3]; let {0 : first, [arr.length - 1] : last} = arr; first // 1 last // 3
三、字符串的解构赋值
①
const [a, b, c, d, e] = 'hello'; a // "h" b // "e" e // "o"
②
let {length : len} = 'hello'; len // 5
四、数值和布尔值的解构赋值
①解构赋值时,如果等号右边是数值和布尔值,则会先转为对象。
//数值和布尔值的包装对象都有toString属性,因此变量s都能取到值 let {toString: s} = 123; s === Number.prototype.toString // true let {toString: s} = true; s === Boolean.prototype.toString // true
②undefined和null无法转为对象
五、函数参数的解构赋值
①传入参数时,数组参数被解构成变量x和y。
function add([x, y]){ return x + y; } add([1, 2]); // 3
②undefined会触发函数参数的默认值
[1, undefined, 3].map((x = 'yes') => x); // [ 1, 'yes', 3 ]
六、圆括号问题(可能导致解构歧义)
①有好几条不能用的,我觉得还是尽量都不用吧。
②可以使用圆括号的情况只有一种:赋值语句的非模式部分,可以使用圆括号
七、用途
①交换变量的值
let x = 1; let y = 2; [x, y] = [y, x];
②从函数返回多个值
// 返回一个数组 function example() { return [1, 2, 3]; } let [a, b, c] = example(); // 返回一个对象 function example() { return { foo: 1, bar: 2 }; } let { foo, bar } = example();
③函数参数的定义
// 参数是一组有次序的值 function f([x, y, z]) { ... } f([1, 2, 3]); // 参数是一组无次序的值 function f({x, y, z}) { ... } f({z: 3, y: 2, x: 1});
④提取JSON数据
let jsonData = { id: 42, status: "OK", data: [867, 5309] }; let { id, status, data: number } = jsonData; console.log(id, status, number); // 42, "OK", [867, 5309]
⑤函数参数的默认值(这样就避免了在函数体内部再写var foo = config.foo || 'default foo';这样的语句。)
jQuery.ajax = function (url, { async = true, beforeSend = function () {}, cache = true, complete = function () {}, crossDomain = false, global = true, // ... more config }) { // ... do stuff };
⑥遍历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 // 获取键名 for (let [key] of map) { // ... } // 获取键值(value前面还有逗号) for (let [,value] of map) { // ... }
⑦输入模块的指定方法
const { SourceMapConsumer, SourceNode } = require("source-map");