001-es6變量聲明、解構賦值、解構賦值主要用途
一、基本語法
1.1、聲明變量的六種方法
參看地址:http://es6.ruanyifeng.com/#docs/let
let:局部變量,塊級作用域,聲明前使用報錯
var:全局變量,聲明前使用 undefined
const:
聲明一個只讀的常量。一旦聲明,常量的值就不能改變。只是內存地址不變,如果是對象,內存不變屬性對應的值可變
function:
import:
class:
1.2、變量解構賦值
參看地址:http://es6.ruanyifeng.com/#docs/destructuring
1.2.1、數組
let [foo, [[bar], baz]] = [1, [[2], 3]]; foo// 1 bar // 2 baz // 3 let [ , , third] = ["foo", "bar", "baz"]; third // "baz" let [x, , y] = [1, 2, 3]; x // 1 y // 3 let [head, ...tail] = [1, 2, 3, 4]; head // 1 tail // [2, 3, 4] let [x, y, ...z] = [‘a‘]; x // "a" y // undefined z // [] let [foo] = []; //foo undefined let [bar, foo] = [1];//foo undefined
如果等號的右邊不是數組(或者嚴格地說,不是可遍歷的結構,參見《Iterator》一章),那麽將會報錯。
支持Set
let [x, y, z] = new Set([‘a‘, ‘b‘, ‘c‘]); x // "a"
function* fibs() { let a = 0; let b = 1; while (true) { yield a; [a, b] = [b, a + b]; } } let [first, second, third, fourth, fifth, sixth] = fibs(); sixth// 5
上面代碼中,fibs
是一個 Generator 函數(參見《Generator 函數》一章),原生具有 Iterator 接口。解構賦值會依次從這個接口獲取值。
默認值
let [foo = true] = []; foo // true let [x, y = ‘b‘] = [‘a‘]; // x=‘a‘, y=‘b‘ let [x, y = ‘b‘] = [‘a‘, undefined]; // x=‘a‘, y=‘b‘
註意,ES6 內部使用嚴格相等運算符(===
),判斷一個位置是否有值。所以,只有當一個數組成員嚴格等於undefined
,默認值才會生效。
如果默認值是一個表達式,那麽這個表達式是惰性求值的,即只有在用到的時候,才會求值。
function f() { console.log(‘aaa‘); } let [x = f()] = [1];
上面代碼中,因為x
能取到值,所以函數f
根本不會執行。上面的代碼其實等價於下面的代碼。
let x; if ([1][0] === undefined) { x = f(); } else { x = [1][0]; }
1.2.2、對象
對象的解構與數組有一個重要的不同。數組的元素是按次序排列的,變量的取值由它的位置決定;而對象的屬性沒有次序,變量必須與屬性同名,才能取到正確的值。
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‘
1.2.3、字符串
字符串也可以解構賦值。這是因為此時,字符串被轉換成了一個類似數組的對象。
const [a, b, c, d, e] = ‘hello‘; a // "h" b // "e" c // "l" d // "l" e // "o"
類似數組的對象都有一個length
屬性,因此還可以對這個屬性解構賦值。
let {length : len} = ‘hello‘; len // 5
1.2.4、數值和布爾值的解構賦值
let {toString: s} = 123; s === Number.prototype.toString // true let {toString: s} = true; s === Boolean.prototype.toString // true
上面代碼中,數值和布爾值的包裝對象都有toString
屬性,因此變量s
都能取到值。
解構賦值的規則是,只要等號右邊的值不是對象或數組,就先將其轉為對象。由於undefined
和null
無法轉為對象,所以對它們進行解構賦值,都會報錯。
let { prop: x } = undefined; // TypeError let { prop: y } = null; // TypeError
1.2.5、函數參數的解構賦值
function add([x, y]){ return x + y; } add([1, 2]); // 3
上面代碼中,函數add
的參數表面上是一個數組,但在傳入參數的那一刻,數組參數就被解構成變量x
和y
。對於函數內部的代碼來說,它們能感受到的參數就是x
和y
。
下面是另一個例子。
[[1, 2], [3, 4]].map(([a, b]) => a + b); // [ 3, 7 ]
函數參數的解構也可以使用默認值。
function move({x = 0, y = 0} = {}) { return [x, y]; } move({x: 3, y: 8}); // [3, 8] move({x: 3}); // [3, 0] move({}); // [0, 0] move(); // [0, 0]
上面代碼中,函數move
的參數是一個對象,通過對這個對象進行解構,得到變量x
和y
的值。如果解構失敗,x
和y
等於默認值。
註意,下面的寫法會得到不一樣的結果。
function move({x, y} = { x: 0, y: 0 }) { return [x, y]; } move({x: 3, y: 8}); // [3, 8] move({x: 3}); // [3, undefined] move({}); // [undefined, undefined] move(); // [0, 0]
上面代碼是為函數move
的參數指定默認值,而不是為變量x
和y
指定默認值,所以會得到與前一種寫法不同的結果。
undefined
就會觸發函數參數的默認值。
[1, undefined, 3].map((x = ‘yes‘) => x); // [ 1, ‘yes‘, 3 ]
解構賦值雖然很方便,但是解析起來並不容易。對於編譯器來說,一個式子到底是模式,還是表達式,沒有辦法從一開始就知道,必須解析到(或解析不到)等號才能知道。
由此帶來的問題是,如果模式中出現圓括號怎麽處理。ES6 的規則是,只要有可能導致解構的歧義,就不得使用圓括號。
但是,這條規則實際上不那麽容易辨別,處理起來相當麻煩。因此,建議只要有可能,就不要在模式中放置圓括號。
1.3、主要用途
(1)交換變量的值
let x = 1; let y = 2; [x, y] = [y, x];
(2)從函數返回多個值
函數只能返回一個值,如果要返回多個值,只能將它們放在數組或對象裏返回。有了解構賦值,取出這些值就非常方便。
// 返回一個數組 function example() { return [1, 2, 3]; } let [a, b, c] = example(); // 返回一個對象 function example() { return { foo: 1, bar: 2 }; } let { foo, bar } = example();
(3)函數參數的定義
解構賦值可以方便地將一組參數與變量名對應起來。
// 參數是一組有次序的值 function f([x, y, z]) { ... } f([1, 2, 3]); // 參數是一組無次序的值 function f({x, y, z}) { ... } f({z: 3, y: 2, x: 1});
(4)提取 JSON 數據
解構賦值對提取 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]
(5)函數參數的默認值
jQuery.ajax = function (url, { async = true, beforeSend = function () {}, cache = true, complete = function () {}, crossDomain = false, global = true, // ... more config } = {}) { // ... do stuff };
指定參數的默認值,就避免了在函數體內部再寫var foo = config.foo || ‘default foo‘;
這樣的語句。
(6)遍歷 Map 結構
任何部署了 Iterator 接口的對象,都可以用for...of
循環遍歷。Map 結構原生支持 Iterator 接口,配合變量的解構賦值,獲取鍵名和鍵值就非常方便。
const 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) { // ... }
(7)輸入模塊的指定方法
加載模塊時,往往需要指定輸入哪些方法。解構賦值使得輸入語句非常清晰。
const { SourceMapConsumer, SourceNode } = require("source-map");
001-es6變量聲明、解構賦值、解構賦值主要用途