讀懂 ECMAScript 規格

概述

規格文件是計算機語言的官方標準,詳細描述語法規則和實現方法。git

通常來講,沒有必要閱讀規格,除非你要寫編譯器。由於規格寫得很是抽象和精煉,又缺少實例,不容易理解,並且對於解決實際的應用問題,幫助不大。可是,若是你遇到疑難的語法問題,實在找不到答案,這時能夠去查看規格文件,瞭解語言標準是怎麼說的。規格是解決問題的「最後一招」。github

這對 JavaScript 語言頗有必要。由於它的使用場景複雜,語法規則不統一,例外不少,各類運行環境的行爲不一致,致使奇怪的語法問題層出不窮,任何語法書都不可能囊括全部狀況。查看規格,不失爲一種解決語法問題的最可靠、最權威的終極方法。算法

本章介紹如何讀懂 ECMAScript 6 的規格文件。數組

ECMAScript 6 的規格,能夠在 ECMA 國際標準組織的官方網站(www.ecma-international.org/ecma-262/6.0/)免費下載和在線閱讀。app

這個規格文件至關龐大,一共有 26 章,A4 打印的話,足足有 545 頁。它的特色就是規定得很是細緻,每個語法行爲、每個函數的實現都作了詳盡的清晰的描述。基本上,編譯器做者只要把每一步翻譯成代碼就能夠了。這很大程度上,保證了全部 ES6 實現都有一致的行爲。ide

ECMAScript 6 規格的 26 章之中,第 1 章到第 3 章是對文件自己的介紹,與語言關係不大。第 4 章是對這門語言整體設計的描述,有興趣的讀者能夠讀一下。第 5 章到第 8 章是語言宏觀層面的描述。第 5 章是規格的名詞解釋和寫法的介紹,第 6 章介紹數據類型,第 7 章介紹語言內部用到的抽象操做,第 8 章介紹代碼如何運行。第 9 章到第 26 章介紹具體的語法。函數

對於通常用戶來講,除了第 4 章,其餘章節都涉及某一方面的細節,不用通讀,只要在用到的時候,查閱相關章節便可。下面經過一些例子,介紹如何使用這份規格。oop

相等運算符

相等運算符(==)是一個很讓人頭痛的運算符,它的語法行爲多變,不符合直覺。這個小節就看看規格怎麼規定它的行爲。網站

請看下面這個表達式,請問它的值是多少。ui

0 == null

若是你不肯定答案,或者想知道語言內部怎麼處理,就能夠去查看規格,7.2.12 小節是對相等運算符(==)的描述。

規格對每一種語法行爲的描述,都分紅兩部分:先是整體的行爲描述,而後是實現的算法細節。相等運算符的整體描述,只有一句話。

「The comparison x == y, where x and y are values, produces true or false.」

上面這句話的意思是,相等運算符用於比較兩個值,返回truefalse

下面是算法細節。

  1. ReturnIfAbrupt(x).
  2. ReturnIfAbrupt(y).
  3. If Type(x) is the same as Type(y), then
    Return the result of performing Strict Equality Comparison x === y.
  4. If x is null and y is undefined, return true.
  5. If x is undefined and y is null, return true.
  6. If Type(x) is Number and Type(y) is String,
    return the result of the comparison x == ToNumber(y).
  7. If Type(x) is String and Type(y) is Number,
    return the result of the comparison ToNumber(x) == y.
  8. If Type(x) is Boolean, return the result of the comparison ToNumber(x) == y.
  9. If Type(y) is Boolean, return the result of the comparison x == ToNumber(y).
  10. If Type(x) is either String, Number, or Symbol and Type(y) is Object, then
    return the result of the comparison x == ToPrimitive(y).
  11. If Type(x) is Object and Type(y) is either String, Number, or Symbol, then
    return the result of the comparison ToPrimitive(x) == y.
  12. Return false.

上面這段算法,一共有 12 步,翻譯以下。

  1. 若是x不是正常值(好比拋出一個錯誤),中斷執行。
  2. 若是y不是正常值,中斷執行。
  3. 若是Type(x)Type(y)相同,執行嚴格相等運算x === y
  4. 若是xnullyundefined,返回true
  5. 若是xundefinedynull,返回true
  6. 若是Type(x)是數值,Type(y)是字符串,返回x == ToNumber(y)的結果。
  7. 若是Type(x)是字符串,Type(y)是數值,返回ToNumber(x) == y的結果。
  8. 若是Type(x)是布爾值,返回ToNumber(x) == y的結果。
  9. 若是Type(y)是布爾值,返回x == ToNumber(y)的結果。
  10. 若是Type(x)是字符串或數值或Symbol值,Type(y)是對象,返回x == ToPrimitive(y)的結果。
  11. 若是Type(x)是對象,Type(y)是字符串或數值或Symbol值,返回ToPrimitive(x) == y的結果。
  12. 返回false

因爲0的類型是數值,null的類型是 Null(這是規格4.3.13 小節的規定,是內部 Type 運算的結果,跟typeof運算符無關)。所以上面的前 11 步都得不到結果,要到第 12 步才能獲得false

0 == null // false

數組的空位

下面再看另外一個例子。

const a1 = [undefined, undefined, undefined];
const a2 = [, , ,];

a1.length // 3
a2.length // 3

a1[0] // undefined
a2[0] // undefined

a1[0] === a2[0] // true

上面代碼中,數組a1的成員是三個undefined,數組a2的成員是三個空位。這兩個數組很類似,長度都是 3,每一個位置的成員讀取出來都是undefined

可是,它們實際上存在重大差別。

0 in a1 // true
0 in a2 // false

a1.hasOwnProperty(0) // true
a2.hasOwnProperty(0) // false

Object.keys(a1) // ["0", "1", "2"]
Object.keys(a2) // []

a1.map(n => 1) // [1, 1, 1]
a2.map(n => 1) // [, , ,]

上面代碼一共列出了四種運算,數組a1a2的結果都不同。前三種運算(in運算符、數組的hasOwnProperty方法、Object.keys方法)都說明,數組a2取不到屬性名。最後一種運算(數組的map方法)說明,數組a2沒有發生遍歷。

爲何a1a2成員的行爲不一致?數組的成員是undefined或空位,到底有什麼不一樣?

規格的12.2.5 小節《數組的初始化》給出了答案。

「Array elements may be elided at the beginning, middle or end of the element list. Whenever a comma in the element list is not preceded by an AssignmentExpression (i.e., a comma at the beginning or after another comma), the missing array element contributes to the length of the Array and increases the index of subsequent elements. Elided array elements are not defined. If an element is elided at the end of an array, that element does not contribute to the length of the Array.」

翻譯以下。

"數組成員能夠省略。只要逗號前面沒有任何表達式,數組的length屬性就會加 1,而且相應增長其後成員的位置索引。被省略的成員不會被定義。若是被省略的成員是數組最後一個成員,則不會致使數組length屬性增長。」

上面的規格說得很清楚,數組的空位會反映在length屬性,也就是說空位有本身的位置,可是這個位置的值是未定義,即這個值是不存在的。若是必定要讀取,結果就是undefined(由於undefined在 JavaScript 語言中表示不存在)。

這就解釋了爲何in運算符、數組的hasOwnProperty方法、Object.keys方法,都取不到空位的屬性名。由於這個屬性名根本就不存在,規格里面沒說要爲空位分配屬性名(位置索引),只說要爲下一個元素的位置索引加 1。

至於爲何數組的map方法會跳過空位,請看下一節。

數組的 map 方法

規格的22.1.3.15 小節定義了數組的map方法。該小節先是整體描述map方法的行爲,裏面沒有提到數組空位。

後面的算法描述是這樣的。

  1. Let O be ToObject(this value).
  2. ReturnIfAbrupt(O).
  3. Let len be ToLength(Get(O, "length")).
  4. ReturnIfAbrupt(len).
  5. If IsCallable(callbackfn) is false, throw a TypeError exception.
  6. If thisArg was supplied, let T be thisArg; else let T be undefined.
  7. Let A be ArraySpeciesCreate(O, len).
  8. ReturnIfAbrupt(A).
  9. Let k be 0.
  10. Repeat, while k < len
    a. Let Pk be ToString(k).
    b. Let kPresent be HasProperty(O, Pk).
    c. ReturnIfAbrupt(kPresent).
    d. If kPresent is true, then
    d-1. Let kValue be Get(O, Pk).
    d-2. ReturnIfAbrupt(kValue).
    d-3. Let mappedValue be Call(callbackfn, T, «kValue, k, O»).
    d-4. ReturnIfAbrupt(mappedValue).
    d-5. Let status be CreateDataPropertyOrThrow (A, Pk, mappedValue).
    d-6. ReturnIfAbrupt(status).
    e. Increase k by 1.
  11. Return A.

翻譯以下。

  1. 獲得當前數組的this對象
  2. 若是報錯就返回
  3. 求出當前數組的length屬性
  4. 若是報錯就返回
  5. 若是 map 方法的參數callbackfn不可執行,就報錯
  6. 若是 map 方法的參數之中,指定了this,就讓T等於該參數,不然Tundefined
  7. 生成一個新的數組A,跟當前數組的length屬性保持一致
  8. 若是報錯就返回
  9. 設定k等於 0
  10. 只要k小於當前數組的length屬性,就重複下面步驟
    a. 設定Pk等於ToString(k),即將K轉爲字符串
    b. 設定kPresent等於HasProperty(O, Pk),即求當前數組有沒有指定屬性
    c. 若是報錯就返回
    d. 若是kPresent等於true,則進行下面步驟
    d-1. 設定kValue等於Get(O, Pk),取出當前數組的指定屬性
    d-2. 若是報錯就返回
    d-3. 設定mappedValue等於Call(callbackfn, T, «kValue, k, O»),即執行回調函數
    d-4. 若是報錯就返回
    d-5. 設定status等於CreateDataPropertyOrThrow (A, Pk, mappedValue),即將回調函數的值放入A數組的指定位置
    d-6. 若是報錯就返回
    e. k增長 1
  11. 返回A

仔細查看上面的算法,能夠發現,當處理一個全是空位的數組時,前面步驟都沒有問題。進入第 10 步的 b 時,kpresent會報錯,由於空位對應的屬性名,對於數組來講是不存在的,所以就會返回,不會進行後面的步驟。

const arr = [, , ,];
arr.map(n => {
  console.log(n);
  return 1;
}) // [, , ,]

上面代碼中,arr是一個全是空位的數組,map方法遍歷成員時,發現是空位,就直接跳過,不會進入回調函數。所以,回調函數裏面的console.log語句根本不會執行,整個map方法返回一個全是空位的新數組。

V8 引擎對map方法的實現以下,能夠看到跟規格的算法描述徹底一致。

function ArrayMap(f, receiver) {
  CHECK_OBJECT_COERCIBLE(this, "Array.prototype.map");

  // Pull out the length so that modifications to the length in the
  // loop will not affect the looping and side effects are visible.
  var array = TO_OBJECT(this);
  var length = TO_LENGTH_OR_UINT32(array.length);
  return InnerArrayMap(f, receiver, array, length);
}

function InnerArrayMap(f, receiver, array, length) {
  if (!IS_CALLABLE(f)) throw MakeTypeError(kCalledNonCallable, f);

  var accumulator = new InternalArray(length);
  var is_array = IS_ARRAY(array);
  var stepping = DEBUG_IS_STEPPING(f);
  for (var i = 0; i < length; i++) {
    if (HAS_INDEX(array, i, is_array)) {
      var element = array[i];
      // Prepare break slots for debugger step in.
      if (stepping) %DebugPrepareStepInIfStepping(f);
      accumulator[i] = %_Call(f, receiver, element, i, array);
    }
  }
  var result = new GlobalArray();
  %MoveArrayContents(accumulator, result);
  return result;
}