字符串作为数组的键
当使用字符串作为数组的键时,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中,数组有2种类型:标准数组和关联数组
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.