繁体   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