为什么数组中的字符串索引不会增加“长度"? [英] Why does a string index in an array not increase the 'length'?

查看:50
本文介绍了为什么数组中的字符串索引不会增加“长度"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的示例中,array2.length只是10,而在我看来,它应该是13.

In the example below, the array2.length is only 10, while in my mind, it should be 13.

为什么字符串键"索引不增加数组的length?

Why does the "string keyed" indexes not increase the length of the array?

我可以存储内容并仍然访问它,并且VS调试器显示这些数组已正确存储.那么为什么length没有增加?

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 Array仅在数字上进行索引.设置字符串索引"时,就是在设置对象的属性.这些是等效的:

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' };

这篇关于为什么数组中的字符串索引不会增加“长度"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆