简体   繁体   English

Node.js中的JavaScript / ECMAScript数组是否“稀疏”?

[英]Are JavaScript/ECMAScript arrays “sparse” in Node.js?

My question is the same as Are Javascript arrays sparse? 我的问题与Javascript数组稀疏相同吗? with one difference... 有一点不同......

Are JavaScript arrays sparse, as implemented in Node.js (and/or V8) ? JavaScript节点是否稀疏, 如Node.js(和/或V8)中实现的那样 I had assumed the were, but then I did the following test: 我假设了那些,但后来我做了以下测试:

var testArray = [];
testArray[10000] = 'test';
console.log(testArray);

Returned is 10,000 blank elements, with 'test' at the end. 返回的是10,000个空白元素,最后是“test”。 Is this because of the way the debugging output works, or does Node.js actually allocate memory for the undefined array elements when adding new elements? 这是因为调试输出的工作方式,还是Node.js在添加新元素时实际为未定义的数组元素分配内存?

What you are seeing is not an actual array, just a representation. 你所看到的不是一个真正的数组,只是一个表示。 The console checks for the presence of a length and a splice property and prints the numeric properties of the object, which is why jQuery collections appear to be arrays when logged. 控制台检查是否存在lengthsplice属性,并打印对象的数字属性,这就是jQuery集合在记录时显示为数组的原因。

function RandomThingThatIsDefinitelyNotAnArray() {
    this.splice = function() {};
    this.length = 10;
    this[5] = 5;
}

console.log(new RandomThingThatIsDefinitelyNotAnArray());​
// shows [undefined, undefined, undefined, undefined, undefined, 5]

jsfFiddle for a live demo. jsfFiddle用于现场演示。

Node's util.inspect function specifically checks for sparse arrays to print them like that. Node的util.inspect函数专门检查稀疏数组,以便像那样打印它们。 In fact, it has a test that specifically checks for it . 事实上,它有一个专门检查它的测试 I know this because my full rewrite of node's inspector ultimately didn't make it into core, and lead to my UltraREPL . 我知道这一点,因为我对节点检查员的完全重写最终没有成为核心,并导致我的UltraREPL

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM