我有以下数组:
var arr = [];
console.log(arr.length); //Output: 0
arr["1231321"] = "abcd";
console.log(arr.length); //Output: 1231322
arr["1231321".toString()] = "abcd";
console.log(arr.length); //Output: 1231322
arr["a1231321"] = "abcd";
console.log(arr.length); //Output: 0
arr["1231321a"] = "abcd";
console.log(arr.length); //Output: 0
这是 fiddle :http://jsfiddle.net/HcrcR/
当我将 arr 更改为 var arr = {};
时,它就可以工作了。
但是即使我使用字符串键它也开始从键中推送数据的原因是什么?
最佳答案
I have following array/hashmap:
这是 JavaScript 术语中的数组
。
var arr = [];
console.log(arr.length); //Output: 0
这是预期的,它是一个空数组。
arr["1231321"] = "abcd";
console.log(arr.length); //Output: 1231322
length
属性如此之大的原因是它总是比最高索引 +1
。使用字符串并不重要,Array
和 Object
的键在 JavaScript 中始终是字符串。
The length property of this Array object is a data property whose value is always numerically greater than the name of every deletable property whose name is an array index.
arr["1231321".toString()] = "abcd";
console.log(arr.length); //Output: 1231322
在字符串上调用 toString()
不会执行任何操作(它已经是一个字符串)。
arr["a1231321"] = "abcd";
console.log(arr.length); //Output: 0
同样,您在 Array
上设置了一个看起来不像索引的属性。
arr["1231321a"] = "abcd";
console.log(arr.length); //Output: 0
见上文。没有对字符串进行内部解析来尝试获取数字。
when I change my arr to
var arr = {};
then it works.
这就是对象在 JavaScript 中的工作方式。它们只是一桶值的字符串键。
关于javascript - 为什么即使有字符串键,数组也保留了这么多空间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15212065/