如何通过 JavaScript 中的索引引用数组项?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6605853/
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-10-25 21:14:58  来源:igfitidea点击:

How do I reference an array item by its index in JavaScript?

javascriptarraysmultidimensional-array

提问by Craig

I have a JavaScript array:

我有一个 JavaScript 数组:

Fruit > Banana > Colour > Yellow
               > Size   > Large
               > Cost   > .50
      > Apple  > Colour > Green
               > Size   > Small
               > Cost   > 
alert(Fruit['Banana']['Colour']);
.42

I can get values using:

我可以使用以下方法获取值:

alert(Fruit[0][0]);

How do I get the same value using the indexes?e.g.

如何使用索引获得相同的值?例如

for (var a in Fruit) {
    //var a gives me "Banana" and "Apple"
    for (var b in Fruit[a]){
        //var b gives me "Colour", "Size" and "Cost"
        //Fruit[a][b] gives me the values
    }
}

Thank you everyone you lead me in the right direction, here is the solution I was after:

谢谢你们带领我走向正确方向的每个人,这是我所追求的解决方案:

function getItemByIndex(index, array) {
    var counter = 0;

    for (item in array)
    {
        if (counter == index)
        {
            return item;
        }

        counter++;
    }
}

回答by Kon

I'm a little confused, because you seem to have answered your own question. I also don't know how you have your array(s) set up. But if you take a look at this example, you can see it working here:

我有点困惑,因为你似乎已经回答了你自己的问题。我也不知道你是如何设置阵列的。但是如果你看看这个例子,你会发现它在这里工作:

http://jsfiddle.net/uyNnH/

http://jsfiddle.net/uyNnH/

This assumes that the top level array contains your fruit types and second level array contains each fruit type's properties.

这假设顶级数组包含您的水果类型,第二级数组包含每个水果类型的属性。

Update:

更新

From Mozillaand others:

来自Mozilla其他人

In JavaScript 1.0, you can refer to an object's properties by their property name or by their ordinal index. In JavaScript 1.1 or later, however, if you initially define a property by its name, you must always refer to it by its name, and if you initially define a property by an index, you must always refer to it by its index.

在 JavaScript 1.0 中,您可以通过属性名称或序数索引来引用对象的属性。但是,在 JavaScript 1.1 或更高版本中,如果最初通过名称定义属性,则必须始终通过名称引用它,如果最初通过索引定义属性,则必须始终通过索引引用它。

So the issue is that you declare an associative array, instead of an indexed/ordinal-based one. The only solution I can think of is using a (ugly) forloop. Here's some un-tested pseudo-code:

所以问题是你声明了一个关联数组,而不是一个基于索引/序数的数组。我能想到的唯一解决方案是使用(丑陋的)for循环。这是一些未经测试的伪代码:

var obj = {a:'Aye', b:'Bee', c:'See', d:'Dee'};
for (var prop in obj) {
  alert(prop + '=' + obj[prop]); // No order is guaranteed.
}

回答by maerics

It looks like you are confusing JavaScript array objectswith the fact that allobjects are associative arrays. Note that normal objects (e.g. the "Fruit" object you allude to) do not have an intrinsic ordering of properties (keys) whereas Array objects do (due to the natural ordering of integral indices). Essentially, an Array is just an object with a special "length" property that stores the last integer index (starting from zero) plus one.

看起来您将 JavaScript数组对象所有对象都是关联数组这一事实混淆了。请注意,普通对象(例如您提到的“Fruit”对象)没有属性(键)的内在排序,而 Array 对象有(由于整数索引的自然排序)。本质上,数组只是一个具有特殊“长度”属性的对象,该属性存储最后一个整数索引(从零开始)加一。

Any object's properties will be iterated in arbitrary(e.g. random) order:

任何对象的属性都将以任意(例如随机)顺序迭代:

var arr = ['a', 'b', 'c', 'd', 'e', 'f'];
for (var i=0; i<arr.length; i++) { // i = [0 .. length-1]
  alert(arr + '=' + arr[i]); // Explicitly order as 'a', 'b', 'c'...
}

Strictly speaking, even arrays are not guaranteed by the specification to iterate in natural order using a for-inloop; however, most JavaScript interpreters do so anyway. (Notably, IE8 iterates in the order that indices were assigned, not natural order.) This is why you should always iterate arrays using indices in a plain "for" loop.

严格来说,即使是数组也不能保证使用循环按自然顺序进行迭代for-in;然而,大多数 JavaScript 解释器无论如何都是这样做的。(值得注意的是,IE8 按照分配索引的顺序进行迭代,而不是自然顺序。)这就是为什么您应该始终在简单的“for”循环中使用索引来迭代数组的原因。

##代码##

These differences mean that regardless of how your "Fruit" object is defined there is no reliable way to ensure a strict ordering of keys (e.g. "Banana", "Apple", "Color", "Size", etc.) unless you retain your own ordering separately.

这些差异意味着无论您的“水果”对象如何定义,除非您保留您自己单独订购。

回答by Edgar Villegas Alvarado

You can't, unlessyou copy your string indexes to numeric indexes, but they would be new elements in your array

不能除非您将字符串索引复制到数字索引,但它们将是数组中的新元素

回答by nnnnnn

You don't indicate how you create your array or assign those values, but it sounds like you don't know the difference between a JavaScript array and a JavaScript object.

您没有说明如何创建数组或分配这些值,但听起来您不知道 JavaScript 数组和 JavaScript 对象之间的区别。

An object has properties with keys that are strings, but you can't access those properties with an index integer, only by the key.

对象具有键为字符串的属性,但您不能使用索引整数访问这些属性,只能通过键访问。

An array is a special type of object that provides array functionality like a lengthproperty and some methods like sort(), etc. Array properties are normally assigned with numeric indexes, and the lengthproperty is based on those numerically indexed properties, but because arrays are still objects you can also assign properties with string keys. If you say myArray['banana'] = ..that 'banana' property is not accessible via an index number.

数组是一种特殊类型的对象,它提供诸如length属性之类的数组功能和诸如sort()等的一些方法。数组属性通常分配有数字索引,并且该length属性基于这些数字索引的属性,但由于数组仍然是对象,因此您可以还使用字符串键分配属性。如果您说myArray['banana'] = ..无法通过索引号访问“香蕉”属性。

If you want keys like 'banana' you shouldn't be using an array at all, just use a plain object.

如果你想要像'banana'这样的键,你根本不应该使用数组,只需使用一个普通对象。

There are plenty of articles explaining this in much more depth; here's one I found at random: http://andrewdupont.net/2006/05/18/javascript-associative-arrays-considered-harmful/

有很多文章更深入地解释了这一点;这是我随机找到的一个:http: //andrewdupont.net/2006/05/18/javascript-associative-arrays-thinked-harmful/