一道類數組的面試題

問題

var obj = {
  2: '3',
  8: '9',
  length: 2,
  splice: Array.prototype.splice,
  push: Array.prototype.push
}

obj.push(1);
console.log(obj);
obj.push(2);
console.log(obj);

輸出的結果是

Object {
2: 1
3: 2
8: "9"
length: 4
push: ƒ push()
splice: ƒ splice()
}

筆者擴展了一下

var obj = {
  2: '3',
  8: '9',
  length: 'abc',
  splice: Array.prototype.splice,
  push: Array.prototype.push
}

obj.push(5);
/*
Object { 0: 5
2: "3"
8: "9",
splice: ƒ,
push: ƒ }
*/

var obj = {
  6: '3',
  8: '9',
  length: 2,
  splice: Array.prototype.splice,
  push: Array.prototype.push
}

obj.push(5);

/*
Object { 2: 5
6: "3"
8: "9"
length: 3
push: ƒ
splice: ƒ }
*/

解釋

push 這個方法應該是去識別類數組中的 length 屬性的

  • 如果 length 屬性存在並且爲數字,那就設置 obj[length] 的值,並且 length + 1
  • length 不存在或者不爲數字,那麼從 obj[0] 開始設置,並且 length 被設置爲 1.

ES 設計標準裏說到

解釋一下 ToLength 裏調用了 ToInteger,ToInteger 裏調用 ToNumber,ToNumber 的規則很多,但簡言之無法被轉化數字中的字符串返回 NaN 非數。ToUint32 裏得到結果是非數,那就返回成 +0

If the grammar cannot interpret the String as an expansion of StringNumericLiteral, then the result of ToNumber is NaN.

翻譯:如果此文法無法將字符串解釋爲「字符串數值常量」的擴展,那麼 ToNumber 的結果爲 NaN。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章