JavaScript 引擎在頁面載入時會先做語法分析,程式碼寫得不規範就過不了這一關,這類問題稱為語法錯誤;通過語法分析後才開始執行,執行期間發生的問題則是執行期錯誤。不同引擎對這兩類錯誤的提示方式並不相同。
最典型的案例就是多餘的逗號:
var p = {name:"Jack", age:33,}; // 注意 33 後面多了一個逗號
p.toString = function() {
return "姓名:" + this.name + ",年齡:" + this.age;
};
console.log(p);
alert(p);
Firefox 的引擎會直接忽略這個逗號,語法檢查通過,執行期也不報錯。IE6/IE7 則在語法分析階段就失敗,根本進不到執行階段;IE8 修掉了這個問題,其他瀏覽器 likewise 正常。
因為它太容易不經意產生:手滑多敲一個逗號,或是先定義了含大量屬性的物件/陣列,後來刪掉其中幾項,卻忘了清掉尾端的分隔符。
// 不規範
var p = {name:"Jack", age:33,};
var ary = ["one", "two", "three",];
// 規範
var p = {name:"Jack", age:33};
var ary = ["one", "two", "three"];
var ary = [1, 2,]; console.log(ary.length);
IE6/7/8 輸出 3,IE9 與其他瀏覽器輸出 2。ECMAScript 5 的 11.1.4 條文中明確要求忽略最後一個逗號,但 IE 直到 IE9 才跟上這個規範。
規格原文是這樣寫的:
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.
曾經有人拿這個特性做出一段號稱「全世界最短的 IE 判斷」:
var ie = !-[1,]; alert(ie);
但 IE9 之後這招就失效了。請不要依賴這類 bug 去偵測瀏覽器。
JSON 格式裡,逗號是鍵值對之間的分隔符:
var json = { id: 1, name: 'heero' };
寫程式時很容易畫蛇添足,在最後一組鍵值對後面也補上逗號:
var json = { id: 1, name: 'heero', };
這種寫法在 IE6、IE7 會報錯,IE8 以後以及其他瀏覽器則都能容忍。
直覺上多餘的逗號應該是語法錯誤,但實測所有瀏覽器(含 IE6)都做了相容處理:
var arr = [1, 2, 3,];
for (var i = 0; i < arr.length; i++) { alert(arr[i]); }
非 IE 瀏覽器依序輸出 1、2、3;IE 則輸出 1、2、3、undefined——IE 在那個多餘逗號的位置補了一個 undefined 元素。
若多餘的逗號不在尾端而在中間:
var arr = [1, 2,, 3,];
for (var i = 0; i < arr.length; i++) { alert(arr[i]); }
所有瀏覽器都輸出 1、2、undefined、3,可見處理邏輯一致:在多餘逗號處插入一個 undefined 元素。