Javascript 字符串作为数组的键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8630471/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 06:48:35  来源:igfitidea点击:

Strings as keys of array

javascriptarrays

提问by abuduba

When using strings as keys of an array, consoleis 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.

当使用字符串作为数组的键时,console是否显示没有这些声明值的数组,并且在不显示键为字符串的情况下迭代此值时?,虽然我可以得到它们的价值。

>> 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

I understand that arrays are objects which has implemented some kind of 'enumerate' interface in JavaScript's engine.

我知道数组是在 JavaScript 引擎中实现了某种“枚举”接口的对象。

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.

最有趣的是解释器不会抛出警告或错误,所以我花了一些时间寻找数据可能丢失的地方。

回答by Darin Dimitrov

In javascript there are 2 type of arrays: standard arrays and associative arrays

在javascript中有两种类型的数组:标准数组和关联数组

  • [ ]- standard array - 0 based integer indexes only
  • { }- associative array - javascript objects where keys can be any strings
  • [ ]- 标准数组 - 仅基于 0 的整数索引
  • { }- 关联数组 - javascript 对象,其中键可以是任何字符串

So when you define:

所以当你定义:

var arr = [ 0, 1, 2, 3 ];

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 arrobject (everything is object in javascript). But you are not adding an element to the standard array.

您正在定义一个标准数组,其中索引只能是整数。当你这样做arr["something"],因为something(这是你作为指数使用什么)是不是你基本上是定义一个属性到一个整数arr对象(一切都在JavaScript对象)。但是您没有向标准数组添加元素。

回答by fanaugen

for( var i = arr.length; i--; console.log( arr[ i ] ) );

for( var i = arr.length; i--; console.log( arr[ i ] ) );

This will only give you the numeric indices, of course, but you can still loop over both numeric indices andstring keys of your array like this:

当然,这只会为您提供数字索引,但您仍然可以像这样循环遍历数组的数字索引字符串键:

for (var x in arr) {
    console.log(x + ": " + arr[x]);
}
/* (console output):
     0: 0
     1: 1
     2: 2
     3: 3
     something: aught
*/