作者:beng83790si | 来源:互联网 | 2023-05-16 09:55
Couldsomeoneexplainthis(strange)behavior?Whyisthelengthinthefirstexample3andnot2,a
Could someone explain this (strange) behavior? Why is the length in the first example 3 and not 2, and most importantly, why is the length in the second example 0? As long as the keys are numerical, length works. When they are not, length is 0. How can I get the correct length from the second example? Thank you.
有人能解释这种奇怪的行为吗?为什么第一个例子中的长度是3而不是2,最重要的是,为什么第二个例子中的长度是0?只要键是数值的,长度就可以。当它们不相等时,长度为0。如何从第二个例子中得到正确的长度?谢谢你!
a = [];
a["1"] = {"string1":"string","string2":"string"};
a["2"] = {"string1":"string","string2":"string"};
alert(a.length); // returns 3
b = [];
b["key1"] = {"string1":"string","string2":"string"};
b["key2"] = {"string1":"string","string2":"string"};
alert(b.length); // returns 0
3 个解决方案
84
One thing to note is that there is a difference between regular arrays and associative arrays. In regular arrays (real arrays), the index has to be an integer. On the other hand, associative arrays can use strings as an index. You can think of associative arrays as a map if you like. Now, also note, true arrays always start from zero. Thus in your example, you created an array in the following manner:
需要注意的一点是,常规数组和关联数组之间存在差异。在常规数组(实数组)中,索引必须是整数。另一方面,关联数组可以使用字符串作为索引。如果愿意,可以将关联数组看作映射。注意,真正的数组总是从0开始。因此,在您的示例中,您以以下方式创建了一个数组:
a = [];
a["1"] = {"string1":"string","string2":"string"};
a["2"] = {"string1":"string","string2":"string"}
Javascript was able to convert your string indexes into numbers, hence, your code above becomes:
Javascript能够将字符串索引转换成数字,因此,上面的代码变成:
a = [];
a[1] = {"blah"};
a[2] = {"blah"};
But remember what i said earlier: True arrays start from zero. Therefore, the Javascript interpreter automatically assigned a[0] to the undefined. Try it out in either firebug or the chrome/safari console, and you will see something like this when you try to print "a". You should get something like "[undefined, Object, Object]. Hence the size 3 not 2 as you expected.
但是记住我之前说过的:真正的数组从0开始。因此,Javascript解释器自动将[0]分配给未定义的。在firebug或chrome/safari控制台中尝试一下,当您尝试打印“a”时,您将看到类似的内容。您应该得到“[未定义的、对象、对象]”。因此尺寸是3而不是2。
In your second example, i am pretty sure you are trying to simulate the use of an associated array, which essentially is adding properties to an object. Remember associated arrays enable you to use strings as a key. So in other terms, you are adding a property to the object. So in your example:
在第二个示例中,我非常确定您正在尝试模拟关联数组的使用,它实际上是向对象添加属性。记住关联数组允许您使用字符串作为键。换句话说,就是向对象添加属性。在你的例子:
b["key1"] = {"string1":"string","string2":"string"};
this really means:
这个的意思是:
b.key1 = {"string1":"string","string2":"string"};
Initializing b =[] simply creates an array, but your assignment doesn't populate the array. It simply gives "b" extra properties. Hope this helps.. :-)
初始化b =[]只是创建一个数组,但您的赋值并不填充该数组。它只是给了b额外的属性。希望这可以帮助. .:-)