一、数组
- 解构:按照一定模式,从数组和对象中提取值,对变量进行赋值。
// 本质"模式匹配",只要等号两边模式相同,左边变量就会被赋对应值。
let [a, b, c] = [1, 2, 3];
let [foo, [[bar], baz]] = [1, [[2], 3]]
foo //1
bar //2
baz //3
let [foo] = []
foo
- 如果等号的右边不是数组(不可遍历的结构),将会报错。
let [foo] = 1
let [foo] = null
let [foo] = {}
let[x, y, z] = new Set(['a', 'b', 'c']);
x
let [foo = true] = [];
foo //true
- ES6内部使用严格相等运算符(===),判断一个位置是否有值。所以,只有当一个数组成员严格等于undefined,默认值才会生效。
let [x=1] =[undefined];
x
let [x=1] = [null]
x
let [x = 1, y = x] = []
let [x = 1, y = x] = [2]
let [x = 1, y = x] = [1, 2]
let [x = y, y = 1] = []
二、对象
- 数组的元素时按次序排列的,变量的取值由它的位置决定;而对象的属性没有次序,变量必须与属性同名,才能取到正确的值。
let {bar, foo} = {foo:'aaa', bar:'bbb'};
foo //"aaa"
bar //"bbb"
- 若变量没有对应的属性名,会导致取不到值,最后等于undefined。(解构失败)
let {baz} = {foo:"aaa"};
baz //undefined
- 对象的解构赋值,可以很方便地将现有对象的方法,赋值到某个变量。
const {log} = console;
log('hello')
let obj = {first:'hello', last:'world'};
let {first:f, last:l} = obj;
f //"hello"
l //"world"
- 解构也可用于嵌套解构的对象
- 对象的解构赋值可以取到继承的属性
const obj1 = {}
const obj2 = {foo:'bar'}
Object.setPrototypeOf(obj1,obj2)
const {foo} = obj1
foo //"bar"
let x;
{x} = {x:1}
({x} = {x:1})
三、字符串
- 字符串被换成了一个类似数组的对象,类似数组的对象都有一个length属性,因此可以对这个属性解构赋值。
const [a, b, c] = "hi!"
a
b
c
let {length:len} = "hello";
len
四、数值和布尔值
- 解构赋值时如果等号右边是数值和布尔值,则会先转化为对象
let {toString: s} = 123;
s === Number.prototype.toString
let {prop:x} = undefined
let {prop:y} = null
五、函数参数
function add([x, y]){
return x + y
}
add([1, 2])
[[1, 2], [3, 4]].map(([a, b]) => a + b)
// [ 3, 7 ]
六、圆括号问题
- 变量声明语句
// 全部报错
let [(a)] = [1];
let {x: (c)} = {};
let ({x: c}) = {};
let {(x: c)} = {};
let {(x): c} = {};
let { o: ({ p: p }) } = { o: { p: 2 } };
- 函数参数
function f([(z)]) { return z; }
function f([z,(x)]) { return x; }
- 赋值语句的模式
// 全部报错
({ p: a }) = { p: 42 };
([a]) = [5];
// 报错
[({ p: a }), { x: c }] = [{}, {}];
- 可以使用圆括号的情况
赋值语句的非模式部分,可以使用。
[(b)] = [3];
({ p: (d) } = {});
[(parseInt.prop)] = [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});
let jsonData = {
id: 42,
status: "OK",
data: [867, 5309]
};
let { id, status, data: number } = jsonData;
console.log(id, status, number);
// 42, "OK", [867, 5309]
jQuery.ajax = function (url, {
async = true,
beforeSend = function () {},
cache = true,
complete = function () {},
crossDomain = false,
global = true,
// ... more config
} = {}) {
// ... do stuff
}
const map = new Map();
map.set('first', 'hello');
map.set('second', 'world');
for (let [key, value] of map) {
console.log(key + " is " + value);
}
for (let [key] of map) {
}
for (let [,value] of map) {
}
const { SourceMapConsumer, SourceNode } = require("source-map");