簡體   English   中英

Node.js v8 HOLEY 數組意外行為

[英]Node.js v8 HOLEY arrays unexpected behavior

看了Mathias Bynens關於 HOLEY 和PACKED數組的報告后,我做了一些實驗,得到了意想不到的行為。 看兩種情況:

 // CASE #1 const array = [0,1,2,3,4,5,undefined] array.__proto__[6] = 'some value' console.log(array[6]) // "some value" expected but got undefined

 // CASE #2 const array = [0,1,2,3,4,5] array[10] = 'faraway value' array.__proto__[6] = 'some value' console.log(array[6]) // "some value" expected and received

那么,這些情況有什么區別呢? 為什么在第一種情況下它返回undefined而不查看原型鏈?

在第 1 種情況下,您明確地將undefined放入數組中。 因為元素已經存在,所以沒有必要沿着原型鏈向上走。 相比:

var case1 = [0, 1, 2, 3, 4, 5, undefined, 7];
var case2 = [0, 1, 2, 3, 4, 5, , 7];
case1.hasOwnProperty(6);  // true
case2.hasOwnProperty(6);  // false
console.log(case1[6]);  // "undefined", loaded from object
console.log(case2[6]);  // "undefined", because no element was found (not on the object, and not on the prototype chain)
case2.__proto__[6] = "proto value";
console.log(case2[6]);  // "proto_value", loaded from prototype chain

你的情況會發生什么 1

const array = [0,1,2,3,4,5,undefined] //array length is 7
array.__proto__[6] = 'some value' //will not work becasue 6th position already exists and JS will not load it from proto chain

console.log(array[6]) // you will get undefined because you assigned undefined at 6th position

在你的情況下 2

const array = [0,1,2,3,4,5] //length 6
array[10] = 'faraway value' //you added value on position 10, hence values between 6 and 10 is empty
array.__proto__[6] = 'some value' // you pushed value on position 6 using proto

console.log(array[6]) // you will get some value because position 6 is empty and hence JS tried to look into proto chain

所以基本上你可以說的是, __proto__賦值只會在分配的位置為空時才起作用,因此如果位置為空,那么 JS 將在 proto 鏈中查找。

因此,如果array[6]存在,則array.__proto__[6] = 'value'將不起作用或更改現有array[6]值的值,但如果array[6]為空,則執行array.__proto__[6] = 'value'並獲得它會起作用

旁注, 不推薦使用__proto__

未定義的和未定義的之間存在區別。

當您編寫const array = [ 0, undefined ]您正在創建一個雙元素數組,其中第二個索引 (1) 的值為undefined。

相反,如果你寫const array = [ 0, , ]你仍然在創建一個雙元素數組,但它現在是稀疏的,第二個索引(或“鍵”)甚至不存在,即使它小於數組的.length屬性。

由於沒有密鑰,解釋器將改為檢查原型。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM