這篇把我學 ES6 時的筆記整理成一篇:let 和 const 的區塊作用域與暫時性死區、陣列與物件的解構賦值(含預設值和 7 種實用情境)、字串的 Unicode 支援與新方法(includes、repeat、padStart…)、函式預設參數,最後附上 jQuery each 和原生 forEach 的效能比較。範例多參考自阮一峰的《ECMAScript 6 入門》。
let:區塊作用域 只在所在的區塊內有效 1 2 3 4 5 6 7 { let a = 10 ; var b = 1 ; } a b
var 是函式作用域,let 是區塊作用域 :只要有 { } 就是一個區塊。
for 迴圈適合用 let 1 2 3 4 5 6 for (let i = 0 ; i < 10 ; i++) { } console .log (i);
迴圈變數 i 只存在迴圈裡,不會洩漏到外面。而且迴圈的條件部分和迴圈本體是兩個不同的區塊 :
1 2 3 4 5 6 7 for (let i = 0 ; i < 3 ; i++) { let i = 'abc' ; console .log (i); }
印出三次 abc,代表 let i = 0 和 let i = 'abc' 屬於不同的區塊,互不影響。
沒有變數提升:暫時性死區(TDZ) var 宣告的變數可以在宣告前使用(值是 undefined),let 則必須先宣告再使用:
1 2 3 4 5 6 7 console .log (foo); var foo = 2 ;console .log (bar); let bar = 2 ;
只要區塊裡用 let 宣告了變數,這個變數就綁定在這個區塊 ,不受外部同名變數影響。在宣告之前使用它都會報錯,這段區域叫做暫時性死區(Temporal Dead Zone) :
1 2 3 4 5 6 var tmp = 123 ;if (true ) { tmp = 'abc' ; let tmp; }
連 typeof 也不再是百分之百安全的操作:
比較隱晦的例子:
不允許重複宣告 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 function func ( ) { let a = 10 ; var a = 1 ; } function func ( ) { let a = 10 ; let a = 1 ; } function func (arg ) { let arg; } function func (arg ) { { let arg; } }
區塊作用域取代 IIFE 1 2 3 4 5 6 7 function f1 ( ) { let n = 5 ; if (true ) { let n = 10 ; } console .log (n); }
以前為了不汙染全域,要寫立即執行函式(IIFE);有了區塊作用域,一對大括號就夠了:
1 2 3 4 5 6 7 8 9 10 11 (function ( ) { var tmp = ...; ... }()); { let tmp = ...; ... }
區塊裡優先使用函式表達式 在區塊裡宣告函式,不同環境的行為不一致,建議改用函式表達式:
1 2 3 4 5 6 { let a = 'secret' ; let f = function ( ) { return a; }; }
let 必須在大括號裡 1 2 3 4 5 6 7 if (true ) let x = 1 ;if (true ) { let x = 1 ; }
const:常數 const 擁有 let 的所有特性(區塊作用域、暫時性死區、不能重複宣告),再加上:
宣告後不能重新賦值,而且必須給初始值 1 2 3 4 5 6 7 8 const PI = 3.1415 ;PI PI = 3 ;const foo;
其他和 let 相同的規則 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 if (true ) { const MAX = 5 ; } MAX if (true ) { console .log (MAX ); const MAX = 5 ; } var message = "Hello!" ;let age = 25 ;const message = "Goodbye!" ; const age = 30 ;
const 鎖的是「位址」,不是內容 const 保證的是變數指向的記憶體位址 不變。對物件和陣列來說,內容仍然可以修改:
1 2 3 4 5 6 7 8 9 const foo = {};foo.prop = 123 ; foo.prop foo = {}; const a = [];a.push ('Hello' ); a.length = 0 ; a = ['Dave' ];
需要讓物件內容也不能改,要用 Object.freeze()。
陣列的解構賦值 基本用法 1 2 3 4 5 6 7 let a = 1 ;let b = 2 ;let c = 3 ;let [a, b, c] = [1 , 2 , 3 ];
只要等號兩邊的「模式」相同,就會依照位置 賦值:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 let [foo, [[bar], baz]] = [1 , [[2 ], 3 ]];foo bar baz let [ , , third] = ["foo" , "bar" , "baz" ];third let [x, , y] = [1 , 2 , 3 ];x y let [head, ...tail] = [1 , 2 , 3 , 4 ];head tail let [x, y, ...z] = ['a' ];x y z
解構失敗與不完全解構 1 2 3 4 5 6 7 8 9 10 11 12 13 14 let [foo] = [];let [bar, foo] = [1 ];foo let [x, y] = [1 , 2 , 3 ];x y let [a, [b], d] = [1 , [2 , 3 ], 4 ];a b d
等號右邊如果不是可迭代的結構,就會報錯:
1 2 3 4 5 6 let [foo] = 1 ; let [foo] = false ; let [foo] = NaN ; let [foo] = undefined ; let [foo] = null ; let [foo] = {};
反過來,只要有實作 Iterator 介面,例如 Set,都可以用陣列解構:
1 2 let [x, y, z] = new Set (['a' , 'b' , 'c' ]);x
預設值 1 2 3 4 5 let [foo = true ] = [];foo let [x, y = 'b' ] = ['a' ]; let [x, y = 'b' ] = ['a' , undefined ];
ES6 用嚴格相等 === 判斷:只有值 === undefined 時,預設值才會生效 。null 不等於 undefined,所以預設值不會生效:
1 2 3 4 5 let [x = 1 ] = [undefined ];x let [x = 1 ] = [null ];x
預設值如果是表達式,是惰性求值 的,只有在用到時才會執行:
1 2 3 4 5 function f ( ) { console .log ('aaa' ); } let [x = f ()] = [1 ];
等同於:
1 2 3 4 5 6 let x;if ([1 ][0 ] === undefined ) { x = f (); } else { x = [1 ][0 ]; }
預設值可以引用其他變數,但那個變數必須已經宣告:
1 2 3 4 let [x = 1 , y = x] = []; let [x = 1 , y = x] = [2 ]; let [x = 1 , y = x] = [1 , 2 ]; let [x = y, y = 1 ] = [];
物件的解構賦值 1 2 3 let { foo, bar } = { foo : 'aaa' , bar : 'bbb' };foo bar
和陣列解構的差別:依名稱,不依順序 陣列解構 :依照位置 取值物件解構 :沒有順序,變數必須和屬性同名 才取得到值1 2 3 4 5 6 let { bar, foo } = { foo : 'aaa' , bar : 'bbb' }; foo bar let { baz } = { foo : 'aaa' , bar : 'bbb' }; baz
變數名稱和屬性名稱不同 1 2 3 let { foo : baz } = { foo : 'aaa' , bar : 'bbb' };baz foo
物件解構的機制是:先找到同名屬性,再把值賦給冒號後面的變數 。所以真正被賦值的是 baz,foo 只是用來比對的模式。
預設值 和陣列一樣,屬性值 === undefined 時預設值才會生效 :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 var { x = 3 } = {};x var { x, y = 5 } = { x : 1 };x y var { x : y = 3 } = {};y var { x : y = 3 } = { x : 5 };y var { message : msg = 'Something went wrong' } = {};msg var { x = 3 } = { x : undefined };x var { x = 3 } = { x : null };x
解構賦值的 7 種實用情境 1. 交換變數 1 2 3 let x = 1 ;let y = 2 ;[x, y] = [y, x];
2. 從函式回傳多個值 1 2 3 4 5 6 7 8 9 10 11 function example ( ) { return [1 , 2 , 3 ]; } let [a, b, c] = example ();function example ( ) { return { foo : 1 , bar : 2 }; } let { foo, bar } = example ();
3. 定義函式參數 1 2 3 4 5 6 7 function f ([x, y, z] ) { ... }f ([1 , 2 , 3 ]);function f ({ x, y, z } ) { ... }f ({ z : 3 , y : 2 , x : 1 });
4. 取出 JSON 資料 1 2 3 4 5 6 7 8 9 let jsonData = { id : 42 , status : "OK" , data : [867 , 5309 ] }; let { id, status, data : number } = jsonData;console .log (id, status, number);
5. 函式參數的預設值 1 2 3 4 5 6 7 8 9 10 11 jQuery.ajax = function (url, { async = true , beforeSend = function () {}, cache = true , complete = function () {}, crossDomain = false , global = true , // ... more config } = {} ) { };
不用再在函式裡寫 var foo = config.foo || 'default foo';。
6. 走訪 Map 任何實作 Iterator 介面的結構,都可以用 for...of 走訪,搭配解構取出 key 和 value:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 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) { ... }
7. 引入模組的指定方法 1 const { SourceMapConsumer , SourceNode } = require ("source-map" );
字串的擴充 Unicode 表示法 ES5 的 \uXXXX 只能表示 \u0000 到 \uFFFF,超過範圍的字要用兩個 UTF-16 代理對表示。ES6 加上大括號就能直接表示:
1 2 3 4 5 6 7 8 9 10 "\u0061" "\uD842\uDFB7" "\u20BB7" "\u{20BB7}" "\u{41}\u{42}\u{43}" let hello = 123 ;hell\u{6F} '\u{1F680}' === '\uD83D\uDE80'
同一個字元有六種寫法:
1 2 3 4 5 '\z' === 'z' '\172' === 'z' '\x7A' === 'z' '\u007A' === 'z' '\u{7A}' === 'z'
用 for…of 走訪字串 for...of 能正確辨識超過 0xFFFF 的字元,傳統的 for 迴圈不行:
1 2 3 4 5 6 7 8 9 10 11 12 let text = String .fromCodePoint (0x20BB7 );for (let i = 0 ; i < text.length ; i++) { console .log (text[i]); } for (let i of text) { console .log (i); }
JSON.stringify() 的改進 JSON.stringify() 以前可能回傳 0xD800 到 0xDFFF 之間的單獨代理字元,產生不合法的 UTF-8。ES2019 改成遇到單獨或順序不對的代理字元時,回傳跳脫後的字串:
1 2 JSON .stringify ('\u{D834}' ) JSON .stringify ('\uDF06\uD834' )
字串的新方法 String.fromCodePoint() ES5 的 String.fromCharCode() 無法辨識超過 0xFFFF 的碼點,最高位會被捨棄:
1 2 3 4 5 6 7 8 9 String .fromCharCode (0x20BB7 )String .fromCodePoint (0x20BB7 )String .fromCodePoint (0x78 , 0x1f680 , 0x79 ) === 'x\uD83D\uDE80y'
String.raw() 回傳斜線不被跳脫的原始字串,常用在模板字串的標籤:
1 2 3 4 String .raw `Hi\n${2 + 3 } !` String .raw ({ raw : ['foo' , 'bar' ] }, 1 + 2 )
它的實作大致如下:
1 2 3 4 5 6 7 8 9 String .raw = function (strings, ...values ) { let output = '' ; let index; for (index = 0 ; index < values.length ; index++) { output += strings.raw [index] + values[index]; } output += strings.raw [index]; return output; };
includes()、startsWith()、endsWith() 以前只能用 indexOf 判斷是否包含某個字串,ES6 多了三個語意清楚的方法:
1 2 3 4 5 6 7 8 9 10 let s = 'Hello world!' ;s.startsWith ('Hello' ) s.endsWith ('!' ) s.includes ('o' ) s.startsWith ('world' , 6 ) s.endsWith ('Hello' , 5 ) s.includes ('Hello' , 6 )
repeat() 1 2 3 4 5 6 7 8 9 10 11 12 'x' .repeat (3 ) 'hello' .repeat (2 ) 'na' .repeat (0 ) 'na' .repeat (2.9 ) 'na' .repeat (Infinity ) 'na' .repeat (-1 ) 'na' .repeat (-0.9 ) 'na' .repeat (NaN ) 'na' .repeat ('na' ) 'na' .repeat ('3' )
padStart()、padEnd() 補齊字串長度:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 'x' .padStart (5 , 'ab' ) 'x' .padStart (4 , 'ab' ) 'x' .padEnd (5 , 'ab' ) 'x' .padEnd (4 , 'ab' ) 'xxx' .padStart (2 , 'ab' ) 'abc' .padStart (10 , '0123456789' ) 'x' .padStart (4 ) 'x' .padEnd (4 )
實用情境:補零和提示格式
1 2 3 4 5 '1' .padStart (10 , '0' ) '123456' .padStart (10 , '0' ) '12' .padStart (10 , 'YYYY-MM-DD' ) '09-12' .padStart (10 , 'YYYY-MM-DD' )
trimStart()、trimEnd() 1 2 3 4 5 const s = ' abc ' ;s.trim () s.trimStart () s.trimEnd ()
函式的預設參數 基本用法 ES6 之前要在函式裡寫 y = y || 'World',但這樣傳入空字串也會被換成預設值。ES6 可以直接在參數上設定預設值:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 function log (x, y = 'World' ) { console .log (x, y); } log ('Hello' ) log ('Hello' , 'China' ) log ('Hello' , '' ) function Point (x = 0 , y = 0 ) { this .x = x; this .y = y; } const p = new Point ();p
注意事項 參數已經是宣告過的變數,函式裡不能再用 let 或 const 宣告同名變數:
1 2 3 4 function foo (x = 5 ) { let x = 1 ; const x = 2 ; }
使用預設參數時,不能有同名參數:
1 2 3 4 5 6 7 8 9 10 function foo (x, x, y ) { } function foo (x, x, y = 1 ) { }
預設值是惰性求值 的:每次呼叫都會重新計算,不會沿用上一次的結果:
1 2 3 4 5 6 7 8 let x = 99 ;function foo (p = x + 1 ) { console .log (p); } foo () x = 100 ; foo ()
搭配物件解構 1 2 3 4 5 6 7 8 function foo ({ x, y = 5 } ) { console .log (x, y); } foo ({}) foo ({ x : 1 }) foo ({ x : 1 , y : 2 }) foo ()
只用物件解構時,呼叫時不能省略參數。實際例子:
1 2 3 4 5 6 function fetch (url, { body = '' , method = 'GET' , headers = {} } ) { console .log (method); } fetch ('http://example.com' , {}) fetch ('http://example.com' )
想讓第二個參數可以省略,就再替整個物件加一個**預設值 {}**,形成「雙重預設值」:
1 2 3 4 5 function fetch (url, { body = '' , method = 'GET' , headers = {} } = {} ) { console .log (method); } fetch ('http://example.com' )
附錄:jQuery each 與原生 forEach 效能比較 測試頁面載入 jQuery 和 5 個 <link> 標籤,分別用原生 API 和 jQuery 走訪:
1 2 3 4 5 6 var linkEls = document .querySelectorAll ('link[href*=".min.css"]' );[].forEach .call (linkEls, function (el ) {}); $('link[href*=".min.css"]' ).each (function ( ) {});
結果:
方法 每秒執行次數 forEach(原生)338,628 ops/sec ±2.48% each(jQuery)265,555 ops/sec ±3.18%
原生 forEach 快了約 27%。現代瀏覽器的 NodeList 本身就有 forEach,可以直接寫 linkEls.forEach(el => { ... }),不需要 [].forEach.call。