JavaScript ES6 重點整理:let、const、解構賦值、字串新方法與函式預設參數

這篇把我學 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 // ReferenceError: a is not defined.
b // 1

var 是函式作用域,let 是區塊作用域:只要有 { } 就是一個區塊。

for 迴圈適合用 let

1
2
3
4
5
6
for (let i = 0; i < 10; i++) {
// ...
}

console.log(i);
// ReferenceError: i is not defined

迴圈變數 i 只存在迴圈裡,不會洩漏到外面。而且迴圈的條件部分和迴圈本體是兩個不同的區塊:

1
2
3
4
5
6
7
for (let i = 0; i < 3; i++) {
let i = 'abc';
console.log(i);
}
// abc
// abc
// abc

印出三次 abc,代表 let i = 0 和 let i = 'abc' 屬於不同的區塊,互不影響。

沒有變數提升:暫時性死區(TDZ)

var 宣告的變數可以在宣告前使用(值是 undefined),let 則必須先宣告再使用:

1
2
3
4
5
6
7
// var 的情況
console.log(foo); // undefined
var foo = 2;

// let 的情況
console.log(bar); // ReferenceError
let bar = 2;

只要區塊裡用 let 宣告了變數,這個變數就綁定在這個區塊,不受外部同名變數影響。在宣告之前使用它都會報錯,這段區域叫做暫時性死區(Temporal Dead Zone):

1
2
3
4
5
6
var tmp = 123;

if (true) {
tmp = 'abc'; // ReferenceError
let tmp;
}

連 typeof 也不再是百分之百安全的操作:

1
2
typeof x; // ReferenceError
let x;

比較隱晦的例子:

1
2
var y = y; // 不報錯,y 是 undefined
let z = z; // ReferenceError: Cannot access 'z' before initialization

不允許重複宣告

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;
}

// 報錯:參數和 let 在同一個區塊
function func(arg) {
let arg;
}

// 不報錯:let 在內層區塊
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); // 5,外層的 n 不受內層影響
}

以前為了不汙染全域,要寫立即執行函式(IIFE);有了區塊作用域,一對大括號就夠了:

1
2
3
4
5
6
7
8
9
10
11
// IIFE 寫法
(function () {
var tmp = ...;
...
}());

// ES6 寫法
{
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 // 3.1415

PI = 3;
// TypeError: Assignment to constant variable.

const foo;
// SyntaxError: Missing initializer in const declaration

其他和 let 相同的規則

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// 只在宣告的區塊內有效
if (true) {
const MAX = 5;
}
MAX // ReferenceError: MAX is not defined

// 只能在宣告後使用
if (true) {
console.log(MAX); // ReferenceError
const MAX = 5;
}

// 不能重複宣告
var message = "Hello!";
let age = 25;
const message = "Goodbye!"; // SyntaxError
const age = 30; // SyntaxError

const 鎖的是「位址」,不是內容

const 保證的是變數指向的記憶體位址不變。對物件和陣列來說,內容仍然可以修改:

1
2
3
4
5
6
7
8
9
const foo = {};
foo.prop = 123; // 可以新增屬性
foo.prop // 123
foo = {}; // TypeError: "foo" is read-only

const a = [];
a.push('Hello'); // ok
a.length = 0; // ok
a = ['Dave']; // error

需要讓物件內容也不能改,要用 Object.freeze()。

陣列的解構賦值

基本用法

1
2
3
4
5
6
7
// ES6 之前
let a = 1;
let b = 2;
let c = 3;

// ES6
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 // 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 // []

解構失敗與不完全解構

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// 解構失敗:對應不到值,就是 undefined
let [foo] = [];
let [bar, foo] = [1];
foo // undefined

// 不完全解構:左邊只取右邊的一部分,仍然成功
let [x, y] = [1, 2, 3];
x // 1
y // 2

let [a, [b], d] = [1, [2, 3], 4];
a // 1
b // 2
d // 4

等號右邊如果不是可迭代的結構,就會報錯:

1
2
3
4
5
6
let [foo] = 1;          // TypeError
let [foo] = false; // TypeError
let [foo] = NaN; // TypeError
let [foo] = undefined; // TypeError
let [foo] = null; // TypeError
let [foo] = {}; // TypeError

反過來,只要有實作 Iterator 介面,例如 Set,都可以用陣列解構:

1
2
let [x, y, z] = new Set(['a', 'b', 'c']);
x // "a"

預設值

1
2
3
4
5
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 時,預設值才會生效。null 不等於 undefined,所以預設值不會生效:

1
2
3
4
5
let [x = 1] = [undefined];
x // 1

let [x = 1] = [null];
x // null

預設值如果是表達式,是惰性求值的,只有在用到時才會執行:

1
2
3
4
5
function f() {
console.log('aaa');
}

let [x = f()] = [1]; // x 有值,f() 不會被執行

等同於:

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] = [];     // 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 還沒宣告就被拿來當 x 的預設值

物件的解構賦值

1
2
3
let { foo, bar } = { foo: 'aaa', bar: 'bbb' };
foo // "aaa"
bar // "bbb"

和陣列解構的差別:依名稱,不依順序

  • 陣列解構:依照位置取值
  • 物件解構:沒有順序,變數必須和屬性同名才取得到值
1
2
3
4
5
6
let { bar, foo } = { foo: 'aaa', bar: 'bbb' }; // 順序不影響
foo // "aaa"
bar // "bbb"

let { baz } = { foo: 'aaa', bar: 'bbb' }; // 沒有同名屬性
baz // undefined

變數名稱和屬性名稱不同

1
2
3
let { foo: baz } = { foo: 'aaa', bar: 'bbb' };
baz // "aaa"
foo // ReferenceError: foo is not defined

物件解構的機制是:先找到同名屬性,再把值賦給冒號後面的變數。所以真正被賦值的是 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 // 3

var { x, y = 5 } = { x: 1 };
x // 1
y // 5

var { x: y = 3 } = {};
y // 3

var { x: y = 3 } = { x: 5 };
y // 5

var { message: msg = 'Something went wrong' } = {};
msg // "Something went wrong"

var { x = 3 } = { x: undefined };
x // 3

var { x = 3 } = { x: null };
x // null,null !== undefined,預設值不生效

解構賦值的 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);
// 42, "OK", [867, 5309]

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
} = {}) {
// ... do stuff
};

不用再在函式裡寫 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);
}
// first is hello
// second is world

// 只取 key
for (let [key] of map) { ... }

// 只取 value
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"        // "a"
"\uD842\uDFB7" // "𠮷"
"\u20BB7" // "₻7",被解讀成 \u20BB + "7"
"\u{20BB7}" // "𠮷"
"\u{41}\u{42}\u{43}" // "ABC"

let hello = 123;
hell\u{6F} // 123,識別字也能用

'\u{1F680}' === '\uD83D\uDE80' // true,大括號表示法和 UTF-16 是等價的

同一個字元有六種寫法:

1
2
3
4
5
'\z' === 'z'      // true
'\172' === 'z' // true
'\x7A' === 'z' // true
'\u007A' === 'z' // true
'\u{7A}' === 'z' // true

用 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}')     // "\"\\ud834\""
JSON.stringify('\uDF06\uD834') // "\"\\udf06\\ud834\""

字串的新方法

String.fromCodePoint()

ES5 的 String.fromCharCode() 無法辨識超過 0xFFFF 的碼點,最高位會被捨棄:

1
2
3
4
5
6
7
8
9
String.fromCharCode(0x20BB7)
// "ஷ",0x20BB7 溢位,變成 0x0BB7

String.fromCodePoint(0x20BB7)
// "𠮷"

// 多個參數會合併成一個字串
String.fromCodePoint(0x78, 0x1f680, 0x79) === 'x\uD83D\uDE80y'
// true

String.raw()

回傳斜線不被跳脫的原始字串,常用在模板字串的標籤:

1
2
3
4
String.raw`Hi\n${2 + 3}!` // "Hi\\n5!"

// `foo${1 + 2}bar` 等同於
String.raw({ raw: ['foo', 'bar'] }, 1 + 2) // "foo3bar"

它的實作大致如下:

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') // true
s.endsWith('!') // true
s.includes('o') // true

// 第二個參數:開始搜尋的位置
s.startsWith('world', 6) // true
s.endsWith('Hello', 5) // true,endsWith 是看「前 n 個字元」
s.includes('Hello', 6) // false

repeat()

1
2
3
4
5
6
7
8
9
10
11
12
'x'.repeat(3)      // "xxx"
'hello'.repeat(2) // "hellohello"
'na'.repeat(0) // ""
'na'.repeat(2.9) // "nana",小數會無條件捨去

'na'.repeat(Infinity) // RangeError
'na'.repeat(-1) // RangeError

'na'.repeat(-0.9) // "",-1 到 0 之間的小數會被當成 0
'na'.repeat(NaN) // "",NaN 等同 0
'na'.repeat('na') // "",字串會先轉成數字
'na'.repeat('3') // "nanana"

padStart()、padEnd()

補齊字串長度:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
'x'.padStart(5, 'ab') // 'ababx'
'x'.padStart(4, 'ab') // 'abax'
'x'.padEnd(5, 'ab') // 'xabab'
'x'.padEnd(4, 'ab') // 'xaba'

// 原字串長度已經 >= 目標長度,回傳原字串
'xxx'.padStart(2, 'ab') // 'xxx'

// 補的字串太長,會被截斷
'abc'.padStart(10, '0123456789') // '0123456abc'

// 沒有第二個參數,用空格補
'x'.padStart(4) // ' x'
'x'.padEnd(4) // 'x '

實用情境:補零和提示格式

1
2
3
4
5
'1'.padStart(10, '0')      // "0000000001"
'123456'.padStart(10, '0') // "0000123456"

'12'.padStart(10, 'YYYY-MM-DD') // "YYYY-MM-12"
'09-12'.padStart(10, 'YYYY-MM-DD') // "YYYY-09-12"

trimStart()、trimEnd()

1
2
3
4
5
const s = '  abc  ';

s.trim() // "abc"
s.trimStart() // "abc "
s.trimEnd() // " abc"

函式的預設參數

基本用法

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') // Hello World
log('Hello', 'China') // Hello China
log('Hello', '') // Hello

function Point(x = 0, y = 0) {
this.x = x;
this.y = y;
}

const p = new Point();
p // { x: 0, y: 0 }

注意事項

參數已經是宣告過的變數,函式裡不能再用 let 或 const 宣告同名變數:

1
2
3
4
function foo(x = 5) {
let x = 1; // error
const x = 2; // error
}

使用預設參數時,不能有同名參數:

1
2
3
4
5
6
7
8
9
10
// 不報錯(非嚴格模式)
function foo(x, x, y) {
// ...
}

// 報錯
function foo(x, x, y = 1) {
// ...
}
// SyntaxError: Duplicate parameter name not allowed in this context

預設值是惰性求值的:每次呼叫都會重新計算,不會沿用上一次的結果:

1
2
3
4
5
6
7
8
let x = 99;
function foo(p = x + 1) {
console.log(p);
}

foo() // 100
x = 100;
foo() // 101

搭配物件解構

1
2
3
4
5
6
7
8
function foo({ x, y = 5 }) {
console.log(x, y);
}

foo({}) // undefined 5
foo({ x: 1 }) // 1 5
foo({ x: 1, y: 2 }) // 1 2
foo() // TypeError: Cannot destructure property 'x' of 'undefined'

只用物件解構時,呼叫時不能省略參數。實際例子:

1
2
3
4
5
6
function fetch(url, { body = '', method = 'GET', headers = {} }) {
console.log(method);
}

fetch('http://example.com', {}) // "GET"
fetch('http://example.com') // 報錯

想讓第二個參數可以省略,就再替整個物件加一個**預設值 {}**,形成「雙重預設值」:

1
2
3
4
5
function fetch(url, { body = '', method = 'GET', headers = {} } = {}) {
console.log(method);
}

fetch('http://example.com') // "GET"

附錄:jQuery each 與原生 forEach 效能比較

測試頁面載入 jQuery 和 5 個 <link> 標籤,分別用原生 API 和 jQuery 走訪:

1
2
3
4
5
6
// ES6 原生
var linkEls = document.querySelectorAll('link[href*=".min.css"]');
[].forEach.call(linkEls, function (el) {});

// jQuery
$('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。