ES6允许按照一定模式,从数组和对象中提取值,对变量进行赋值,这被称为解构(Destructuring)。
数组
数组的元素是按次序排列的,变量的取值由它的位置决定
本质上,这种写法属于“模式匹配”,只要等号两边的模式相同,左边的变量就会被赋予对应的值。
var [foo, [[bar], baz]] = [1, [[2], 3]];
foo // 1
bar // 2
baz // 3
var [,,third] = ["foo", "bar", "baz"];
third // "baz"
var [head, ...tail] = [1, 2, 3, 4];
head // 1
tail // [2, 3, 4]
//如果解构不成功,变量的值就等于undefined。
var [foo] = [];
var [foo] = 1;
var [foo] = 'Hello';
var [foo] = false;
var [foo] = NaN;
//如果对undefined 或null 进行解构,就会报错。
//是因为解构只能用于数组或对象。其他原始类型的值都可以转为相应的对象,但是,undefined和null不能转为对象,因此报错。
var [foo] = undefined;
var [foo] = null;
//解构赋值允许指定默认值。
var [foo = true] = [];
foo // true
对象
对象的属性没有次序,变量必须与属性同名,才能取到正确的值
//等号左边的两个变量的次序,与等号右边两个同名属性的次序不一致,但是对取值完全没有影响
var {
bar , foo } = {
foo:"aaa",bar:"bbb" };
foo , bar //“aaa”,"bbb"
//变量没有对应的同名属性,导致取不到值,最后等于undefined
var {
baz } = {
foo: "aaa", bar: "bbb" };
baz // undefined
//解构也可以用于嵌套结构的对象
var o = {
p: [
"Hello",
{
y: "World" }
]
};
var {
p: [x, {
y }] } = o;
x // "Hello"
y // "World"
//指定默认值
var {
x = 3 } = {
};
x // 3
用途
//1. 交换变量的值
[a,b] = [b,a]
//2. 从函数返回多个值
function test(){
//返回的是数组
return [1,2,3]
}
var [a,b,c] = test();
function test(){
//返回的是对象
return {
key1:"value1",key2:"value2"}
}
var {
key1,key2} = test();
//3. 函数参数的定义
function f({
x,y,z}){
//......
}
f({
x:1,y:2,z:3}); //对提取JSON对象中的数据,尤其有用
//4. 函数参数的默认值
jQuery.ajax = function (url, {
async = true,
beforeSend = function () {
},
cache = true,
complete = function () {
},
crossDomain = false,
global = true,
// ... more config
}) {
// ... do stuff
};
//5. 遍历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) {
// 获取键名
// ...
}
for (let [,value] of map) {
// 获取键值
// ...
}
//6. 输入模块的指定方法
//加载模块时,往往需要指定输入哪些方法。解构赋值使得输入语句非常清晰。
const {
SourceMapConsumer, SourceNode } = require("source-map");