为什么javascript数组中的字符串索引不会增加长度大小? [英] Why does a string index in a javascript array not increase the length size?
问题描述
在下面的例子中,array2.length只有十,在我看来,它应该是13.为什么字符串键入索引不会增加数组的长度?我可以存储并仍可访问它,VS调试器显示这些数组正确存储。那么为什么长度没有增加?
In the example below, the array2.length is only ten, when in my mind, it should be 13. Why does the "string keyed" indexes not increase the length of the array? I can store things and still access it, and the VS debugger shows that those arrays are being stored properly. So why is the length not increased?
var array2 = new Array();
array2["a"] = new Array();
array2["b"] = new Array();
array2["c"] = new Array();
for (var i = 0; i < 10; ++i)
array2[i] = new Array();
var nothing = "";
for (var i = 0; i < array2.length; ++i)
nothing = "";
推荐答案
Javascript数组不能包含字符串索引。 Javascript 数组
仅以数字方式编入索引。设置字符串索引时,您将设置对象的属性。这些是等价的:
Javascript arrays cannot have "string indexes". A Javascript Array
is exclusively numerically indexed. When you set a "string index", you're setting a property of the object. These are equivalent:
array.a = 'foo';
array['a'] = 'foo';
这些属性不属于数组的数据存储。
Those properties are not part of the "data storage" of the array.
如果你想要关联数组,你需要使用一个对象:
If you want "associative arrays", you need to use an object:
var obj = {};
obj['a'] = 'foo';
也许最简单的可视化使用文字符号而不是 new Array
:
Maybe the simplest visualization is using the literal notation instead of new Array
:
// numerically indexed Array
var array = ['foo', 'bar', 'baz'];
// associative Object
var dict = { foo : 42, bar : 'baz' };
这篇关于为什么javascript数组中的字符串索引不会增加长度大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!