简体   繁体   English

Javascript:数组不为空,但大小为0

[英]Javascript: Array is not empty but size is 0

I create a array in Javascript. 我在Javascript中创建一个数组。 I want to use the array for key-value pair. 我想将数组用于键值对。

I can successfully add new items and delete items but the length of it is always 0. 我可以成功添加新项目并删除项目,但它的长度始终为0。

Actually the problem I faced is when I want to convert it to a JSON string, it shows empty string: "[]". 实际上我遇到的问题是当我想将它转换为JSON字符串时,它显示空字符串:“[]”。 I just wonder if they are related. 我只是想知道他们是否相关。 And I would also want to know why I cannot convert it. 我也想知道为什么我不能转换它。

Below is the debug information, It show the array contain 3 objects but the length is 0. The browser is Firefox 44.0 for Ubuntu. 下面是调试信息,它显示数组包含3个对象但长度为0.浏览器是用于Ubuntu的Firefox 44.0。

Thanks! 谢谢!

长度为<code> 0 </ code>且属性<code> 1454073967313 </ code>,<code> 1454073968645 </ code>和<code> 1454073969737 </ code>的数组


Fellow @georg idea, I limited the index into 1000 and leave the rest code as before. 研究员@georg的想法,我将索引限制在1000并将其余代码保留为以前。 Everything works including the JSON part. 一切正常,包括JSON部分。 The next picture shows that in my array, there are actual 4 elements, the maximum index is 805. 下图显示在我的数组中,实际有4个元素,最大索引是805。

在此输入图像描述

One thing I learned is that the length of Javascript Array is not the real size but the maximum index number. 我学到的一件事是Javascript数组的长度不是实际大小,而是最大索引号。

The newest finding, the array is really as long as the largest index number. 最新的发现,数组真的和最大的索引号一样长。 The rest of the element is Null. 元素的其余部分是Null。

This is one of many oddities in javascript. 这是javascript中的许多奇怪之处。

> a = []
[]
> a[4294967295] = 1
1
> a.length
0 // wtf?

The problem is that Array.length is limited to 32 bits, so its max value is 2^32-1 = 4294967295 . 问题是Array.length限制为32位,因此其最大值为2^32-1 = 4294967295 If you provide an index greater than or equal to 4294967295 , the engine creates a new entry in the array, as usual, but refuses to update its length - without throwing any error. 如果您提供的索引大于或等于4294967295 ,引擎会像往常一样在数组中创建一个新条目,但拒绝更新其length - 不会抛出任何错误。 So you end up with a bag of properties, and the length equal to 0. 所以你最终得到一袋属性, length等于0。

As others suggested, you will be better off using objects if you have such large numeric indexes. 正如其他人所建议的那样,如果您拥有如此庞大的数字索引,最好还是使用对象。

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

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