原文鏈接:http://es6.ruanyifeng.com/#docs/destructuring
源碼地址:https://github.com/NalvyBoo/nodesES6
數(shù)組的解構(gòu)賦值
ES6 允許按照一定模式翩隧,從數(shù)組和對象中提取值侈贷,對變量進(jìn)行賦值洞坑,這被稱為解構(gòu)(Destructuring)
常規(guī)賦值
let a = 1;
let b = 2;
let c = 3;
ES6 允許從數(shù)組中提取值,按照對應(yīng)位置,對變量賦值
let [d,e,f] = [1,2,3];
let [foo,[[bar],baz]] = [1,[[2],3]];
console.log(foo,bar,baz); //1 2 3
let [ , , third] = ["foo","bar","baz"];
console.log(third);
let [x,,y] = [1,2,3];
console.log(x,y); //1 3
let [head,...tail] = [1,2,3,4];
console.log(head,tail); // 1 [2,3,4]
let [x0,y0,...z0] = ['a'];
console.log(x0,y0,z0); //a undefined []
let[fo] = [];
console.log(fo); //undefined
let[ba0,fo0] = [1];
console.log(ba0,fo0); //1 undefined
如果等號(hào)的右邊不是數(shù)組(或者嚴(yán)格地說黍翎,不是可遍歷的結(jié)構(gòu))或详,那么將會(huì)報(bào)錯(cuò)。
// 報(bào)錯(cuò)
let [foo] = 1;
let [foo] = false;
let [foo] = NaN;
let [foo] = undefined;
let [foo] = null;
let [foo] = {};
Set 結(jié)構(gòu)也可以使用數(shù)組的解構(gòu)賦值
let[x1,y1,z1] = new Set(['a','b','c']);
console.log(x1); //a
事實(shí)上柒竞,只要某種數(shù)據(jù)結(jié)構(gòu)具有 Iterator 接口政供,都可以采用數(shù)組形式的解構(gòu)賦值
function* fibs(){
let a = 0;
let b = 1;
while(true){
yield a;
[a,b] = [b, a+b];
}
}
let [first,second,third0,fourth,fifth,sixth] = fibs();
console.log(sixth); //5
默認(rèn)值:解構(gòu)賦值允許指定默認(rèn)值
let [foo1 = true] = [];
console.log(foo1); //true
let [x2,y2 = 'b'] = ['a'];
console.log(x2,y2); //a,b
let [x3,y3 = 'd'] = ['c',undefined];
console.log(x3,y3); //c,d
ES6內(nèi)部使用嚴(yán)格相等運(yùn)算符(===)來判斷一個(gè)位置是否有值
如果一個(gè)數(shù)組成員不嚴(yán)格等于 undefined ,默認(rèn)值是不會(huì)生效的
let [x4 = 4] = [undefined];
console.log(x4); //4
let [x5 = 1] = [null];
console.log(x5); //null null不嚴(yán)格等于undefined
如果默認(rèn)值是一個(gè)表達(dá)式,那么這個(gè)表達(dá)式是惰性求值的朽基,即只有在用到的時(shí)候布隔,才會(huì)求值。
function ff(){
console.log("aaa");
}
let [x6 = ff()] = [6];
console.log(x6); //6
默認(rèn)值可以引用解構(gòu)賦值的其他變量稼虎,但該變量必須已經(jīng)聲明
let [x7 = 7,y7 = x7] = [];
console.log(x7,y7); //7 7
let [x8 = 8,y8 = x8] = [8];
console.log(x8,y8); //8 8
let [x9 = y9,y9 = 9] = []; //y9 is not defined
對象的解構(gòu)賦值
對象的屬性沒有次序衅檀,必須與屬性同名,才能取到正確的值霎俩。
let { f2, b2 } = { f2:"aaa",b2:"bbb" };
console.log(f2,b2); // aaa bbb
let { b3 } = { f3:"f3", b33:"b33"};
console.log(b3); // undefined
如果變量名與屬性名不一致哀军,必須寫成下面這樣
let obj = { ofirst:"hello", last:"world" };
let { ofirst: of, last: l } = obj;
console.log(of,l); // hello world
和數(shù)組一樣,解構(gòu)也可以用于嵌套解構(gòu)的對象
let obj2 = {
p:[
'hello',
{ y10: 'world'}
]
};
let { p:[x10, { y10 }] } = obj2;
console.log(x10,y10); //hello world
let obj3 = {};
let arr = [];
({ foo2: obj3.prop, b4: arr[0] } = { foo2: 123, b4: true });
console.log(obj3,arr);//Object {prop: 123} [true]
對象的解構(gòu)也可以指定默認(rèn)值
var { x11: y11 = 11 } = {};
console.log(y11); //11
var { x12: y12 = 1} = { x12: 12 };
console.log(y12); // 12
如果解構(gòu)失敗打却,變量的值等于 undefined
let { foo3 } = { bar3: 'baz' };
console.log(foo3); //undefined
如果解構(gòu)模式是嵌套的對象杉适,而且子對象所在的父屬性不存在,那么將報(bào)錯(cuò)
let { foo4: { bar4 } } = { bar4: "bar4" };// Uncaught TypeError: Cannot match against 'undefined' or 'null'.
字符串的解構(gòu)賦值
const [aa,bb,cc,dd,ee] = 'hello';
console.log(aa,bb,cc,dd,ee); //h e l l o
類似數(shù)組的對象都有一個(gè)length屬性柳击,因此還可以對這個(gè)屬性解構(gòu)賦值
let { length: len } = 'hello';
console.log(len); //5
數(shù)值和布爾值的解構(gòu)賦值
解構(gòu)賦值是猿推,如果等號(hào)右邊是數(shù)值和布爾值,則會(huì)先轉(zhuǎn)為對象
解構(gòu)賦值的規(guī)則是腻暮,只要等號(hào)右邊的值不是對象或數(shù)組彤守,就先將其轉(zhuǎn)為對象
由于undefined和null無法轉(zhuǎn)為對象,所以對它們進(jìn)行解構(gòu)賦值哭靖,都會(huì)報(bào)錯(cuò)
let { toString: s } = 123;
console.log(s,s === Number.prototype.toString);// true
let { toString: s0 } = true;
console.log(s0,s0 === Boolean.prototype.toString);// true
let { prop:x14 } = undefined; //TypeError
let { prop:x15 } = null; //TypeError
函數(shù)參數(shù)的解構(gòu)賦值
function add([x,y]){
return x + y;
}
console.log(add([1,2]));//3
function move({x = 0, y = 0} = {}){
return [x,y];
}
console.log(move({x:3,y:8}));// [3,8]
console.log(move({x:3}));// [3,0]
console.log(move({}));// [0,0]
console.log(move());// [0,0]
不能使用圓括號(hào)的情況
變量聲明語句中具垫,不能帶有圓括號(hào)
//Unexpected token (
let [(a)] = [1];
let {x:(c)} = {};
let {{x:c}} = {};
let {(x:c)} = {};
let {(x):c} = {};
let { o: ({ p:p }) } = { o: { p:2 } };
函數(shù)參數(shù)中,模式不能帶有圓括號(hào)
函數(shù)參數(shù)也屬于變量聲明试幽,因此不能帶有圓括號(hào)
//Unexpected token (
function f([(z)]) { return z; }
賦值語句中筝蚕,不能將整個(gè)模式,或嵌套模式中的一層铺坞,放在圓括號(hào)之中
({ p:a }) = { p:42 };
[({ p:a }),{ x:c }] = [{},{}];
[({ p:a }),{ x:c }] = [{},{}];
可以使用圓括號(hào)的情況:賦值語句的非模式部分起宽,可以使用圓括號(hào)
let b5;
[(b5)] = [5];
({ p: (d) } = {}) ;
[(parseInt.prop)] = [3];
變量解構(gòu)賦值的用途
交換變量的值
let x20 = 12;
let y20 = 20;
[x20,y20] = [y20,x20];
console.log(x20,y20);// 20 12
從函數(shù)返回多個(gè)值
返回一個(gè)數(shù)組
function example(){
return [1,2,3];
}
let [a21,b21,c21] = example();
console.log(a21,b21,c21); // 1 2 3
返回一個(gè)對象
function example2(){
return{
foo4: 4,
bar5: 5
};
}
let {foo4,bar5} = example2();
console.log(foo4,bar5); // 4 5
函數(shù)參數(shù)的定義:結(jié)構(gòu)函數(shù)可以方便的將一組參數(shù)與變量名對應(yīng)起來
參數(shù)是一組有次序的值
function fff([x22,y22,z22]) {}
fff([1,2,3]);
參數(shù)是一組無次序的值
function ffff({x23,y23,z23}){}
ffff({z23: 3,y23: 2,z23: 1});
提取JSON數(shù)據(jù)
let jsonData = {
id: 42,
status: "OK",
data: [867,5309]
};
let { id,status, data: number } = jsonData;
console.log(id,status,number); //42 "OK" [867, 5309]
函數(shù)參數(shù)的默認(rèn)值
指定參數(shù)的默認(rèn)值,就避免了在函數(shù)體內(nèi)部再寫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結(jié)構(gòu)
任何部署了Iterator接口的對象济榨,都可以用for...of循環(huán)遍歷坯沪。Map結(jié)構(gòu)原生支持Iterator接口,配合變量的解構(gòu)賦值擒滑,獲取鍵名和鍵值就非常方便腐晾。
var 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) {
// ...
}
輸入模塊的指定方法
加載模塊時(shí)藻糖,往往需要指定輸入哪些方法淹冰。解構(gòu)賦值使得輸入語句非常清晰。
const { SourceMapConsumer, SourceNode } = require("source-map");