字符串作为数组的键 [英] Strings as keys of array
问题描述
当使用字符串作为数组的键时,console
显示没有这些声明值的数组,并且当键是字符串的时候通过这个值迭代时没有显示?,虽然我可以获得它们的价值.
When using strings as keys of an array, console
is showing that the array without these declared values and while iterating by this values where keys are string aren't displayed? , although i can get value of them.
>> var arr = [ 0, 1, 2, 3 ];
undefined
>> arr["something"] = "aught";
"aught"
>> arr
[0, 1, 2, 3]
>> arr["something"]
"aught"
>> for( var i = arr.length; i--; console.log( arr[ i ] ) );
3
2
1
0
我知道数组是在 JavaScript 引擎中实现了某种枚举"接口的对象.
I understand that arrays are objects which has implemented some kind of 'enumerate' interface in JavaScript's engine.
最有趣的是解释器不会抛出警告或错误,所以我花了一些时间寻找数据可能丢失的地方.
Most interesting is that interpreter isn't throwing either warning or error, so I spent some time of searching for where data could be lost.
推荐答案
在 JavaScript 中有两种类型的数组:标准数组和关联数组
In javascript there are 2 type of arrays: standard arrays and associative arrays
[ ]
- 标准数组 - 仅基于 0 的整数索引{ }
- 关联数组 - javascript 对象,其中键可以是任何字符串
[ ]
- standard array - 0 based integer indexes only{ }
- associative array - javascript objects where keys can be any strings
所以当你定义:
var arr = [ 0, 1, 2, 3 ];
您正在定义一个标准数组,其中索引只能是整数.当你做 arr["something"]
因为 something
(这是你用作索引的)不是一个整数时,你基本上是在为 arr 定义一个属性
对象(JavaScript 中的一切都是对象).但是您并没有向标准数组添加元素.
you are defining a standard array where indexes can only be integers. When you do arr["something"]
since something
(which is what you use as index) is not an integer you are basically defining a property to the arr
object (everything is object in javascript). But you are not adding an element to the standard array.
这篇关于字符串作为数组的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!