简体   繁体   English

空单元格如何存储在JavaScript的稀疏数组中?

[英]How are empty cells stored in a sparse array in JavaScript?

I have a situation where I may be setting an array cell of a high index without setting any of the cells before it. 我遇到的情况是我可能要设置一个高索引的数组单元,而没有在其之前设置任何单元。

>>> var arr = [];
undefined
>>> arr[5] = 'value';
"filled"
>>> arr
[undefined, undefined, undefined, undefined, undefined, "filled"]

How is such an array stored in memory? 这样的数组如何存储在内存中? Is there space allocated for each undefined value? 是否为每个未定义的值分配了空间?

In my actual project, I may be using very large indices. 在我的实际项目中,我可能使用的索引非常大。 For example, I may set cells 500-800 and 900-1000. 例如,我可以将单元格设置为500-800和900-1000。 I can't use a hash because I need to loop through these non-empty cells and be aware of their index. 我不能使用哈希,因为我需要遍历这些非空单元格并了解它们的索引。 I want to know if fragmenting the array like this will use up a ton of memory for the empty cells. 我想知道是否像这样对数组进行碎片整理会为空单元格占用大量内存。

I can't use a hash because I need to loop through these non-empty cells and be aware of their index. 我不能使用哈希,因为我需要遍历这些非空单元格并了解它们的索引。

What's wrong with the for (x in ...) language construct? for (x in ...)语言构造有什么问题?

EDITED to accomodate vol7ron 's comment: 编辑以适应vol7ron的评论:

var x = {2: "foo", 999: "bar"};

for ( var n in x ) {
    if ( x.hasOwnProperty(n) ) {
        console.log(n);
        console.log(x[n]);
    }
}  

Strapping onto aefxx's answer, you can still iterate: 紧靠aefxx的答案,您仍然可以迭代:

var obj = {500: "foo",  10923: "bar"};
var max = 0;

for (var key in obj)
   max=key>max?key:(max||key);         // get max key

for (var i=0; i<=max; i++)
   console.log(obj[i]);                // output even the undefined

As Phrogz commented, it doesn't allocate for undeclared elements of the array. 正如Phrogz所评论的那样,它不会分配未声明的数组元素。 I'm not certain if that's the case if you explicitly set the element value to undefined (eg arr[somenum] = undefined; ) 我不确定是否确实将元素值设置为undefined(例如arr[somenum] = undefined;

You should probably simply store the max index in a variable and the access your map like this : 您可能应该只将max索引存储在变量中,然后按以下方式访问地图:

for (var i=0; i<=maxIndex; i++) {
 console.log(myMap[i]);
}

Then you'll have the (relative) compacity of the map and the ability to loop through unsetted indexes. 然后,您将具有地图的(相对)兼容性,并能够遍历未设置的索引。

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

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