只要等號兩邊的模式相同,左邊的變量就會被賦予對應的值。javascript
let [a, b, c] = [1, 2, 3];
若是解構不成功,變量的值就等於 undefined
。java
let [foo, [[bar], baz]] = [1, [[2], 3]]; foo // 1 bar // 2 baz // 3 let [ , , third] = ["foo", "bar", "baz"]; third // "baz" let [head, ...tail] = [1, 2, 3, 4]; head // 1 tail // [2, 3, 4] let [x, y, ...z] = ['a']; x // "a" y // undefined z // []
不徹底解構狀況下,解構依然能夠成功。即等號左邊的模式,只匹配一部分的等號右邊的數組。es6
let [a, [b], d] = [1, [2, 3], 4]; a // 1 b // 2 d // 4
解構賦值容許指定默認值json
ES6 內部使用嚴格相等運算符(===
),判斷一個位置是否有值。因此,只有當一個數組成員嚴格等於undefined
,默認值纔會生效。數組
let [x, y = 'b'] = ['a']; // x='a', y='b' let [x, y = 'b'] = ['a', undefined]; // x='a', y='b' let [x = 1] = [null]; // x=null
若是默認值是一個表達式,那麼這個表達式是惰性求值的,即只有在用到的時候,纔會求值。函數
function f() { console.log('aaa'); } let [x = f()] = [1];
上面代碼中,由於 x
能取到值,因此函數 f
根本不會執行。ui
默認值能夠引用解構賦值的其餘變量,但該變量必須已經聲明。code
let [x = 1, y = x] = []; // x=1; y=1 let [x = 1, y = x] = [2]; // x=2; y=2 let [x = 1, y = x] = [1, 2]; // x=1; y=2 let [x = y, y = 1] = []; // ReferenceError: y is not defined
對象的解構與數組有一個重要的不一樣。數組的元素是按次序排列的,變量的取值由它的位置決定;而對象的屬性沒有次序,變量必須與屬性同名,才能取到正確的值。若是解構失敗,變量的值等於 undefined
。對象
let { bar, foo } = { foo: 'aaa', bar: 'bbb' }; foo // "aaa" bar // "bbb" let { baz } = { foo: 'aaa', bar: 'bbb' }; baz // undefined
若是變量名與屬性名不一致,必須寫成下面這樣。繼承
let { foo: baz } = { foo: 'aaa', bar: 'bbb' }; baz // "aaa" let obj = { first: 'hello', last: 'world' }; let { first: f, last: l } = obj; f // 'hello' l // 'world'
也就是說,對象的解構賦值的內部機制,是先找到同名屬性,而後再賦給對應的變量。真正被賦值的是後者,而不是前者。
let { foo: baz } = { foo: 'aaa', bar: 'bbb' }; baz // "aaa" foo // error: foo is not defined
與數組同樣,解構也能夠用於嵌套結構的對象。
let obj = {}; let arr = []; ({ foo: obj.prop, bar: arr[0] } = { foo: 123, bar: true }); obj // {prop:123} arr // [true]
注意,對象的解構賦值能夠取到繼承的屬性。
const obj1 = {}; const obj2 = { foo: 'bar' }; Object.setPrototypeOf(obj1, obj2); const { foo } = obj1; foo // "bar"
對象的解構也能夠指定默認值
默認值生效的條件是,對象的屬性值嚴格等於(===
) undefined
。
var {x, y = 5} = {x: 1}; x // 1 y // 5 var {x = 3} = {x: null}; x // null
若是要將一個已經聲明的變量用於解構賦值,必須將整個解構賦值語句,放在一個圓括號裏面,才能夠正確執行。
let x; {x} = {x: 1}; // SyntaxError: syntax error // 正確的寫法 let x; ({x} = {x: 1});
由於 JavaScript 引擎會將 {x}
理解成一個代碼塊,從而發生語法錯誤。只有不將大括號寫在行首,避免 JavaScript 將其解釋爲代碼塊,才能解決這個問題。
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]
對象的解構賦值,能夠很方便地將現有對象的方法,賦值到某個變量。
加載模塊時,每每須要指定輸入哪些方法。解構賦值使得輸入語句很是清晰。
let { log, sin, cos } = Math; const { SourceMapConsumer, SourceNode } = require("source-map");
參考連接:
變量的解構賦值