简体   繁体   English

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

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

I have a JavaScript array:我有一个 JavaScript 阵列:

Fruit > Banana > Colour > Yellow
               > Size   > Large
               > Cost   > $3.50
      > Apple  > Colour > Green
               > Size   > Small
               > Cost   > $0.42

I can get values using:我可以使用以下方法获取值:

alert(Fruit['Banana']['Colour']);

How do I get the same value using the indexes?如何使用索引获得相同的值? eg例如

alert(Fruit[0][0]);

Thank you everyone you lead me in the right direction, here is the solution I was after:谢谢大家引导我朝着正确的方向前进,这是我所追求的解决方案:

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

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 Mozilla and others :来自Mozilla其他人

In JavaScript 1.0, you can refer to an object's properties by their property name or by their ordinal index.在 JavaScript 1.0 中,您可以通过属性名称或序号索引来引用对象的属性。 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.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) for loop.我能想到的唯一解决方案是使用(丑陋的) for循环。 Here's some un-tested pseudo-code:这是一些未经测试的伪代码:

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

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

        counter++;
    }
}

It looks like you are confusing JavaScript array objects with the fact that all objects are associative arrays .看起来您将 JavaScript数组对象所有对象都是关联的 arrays的事实混淆了。 Note that normal objects (eg 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).请注意,普通对象(例如,您提到的“水果”object)没有属性(键)的内在顺序,而数组对象则有(由于整数索引的自然顺序)。 Essentially, an Array is just an object with a special "length" property that stores the last integer index (starting from zero) plus one.本质上,数组只是一个 object 具有特殊的“长度”属性,该属性存储最后一个 integer 索引(从零开始)加一。

Any object's properties will be iterated in arbitrary (eg random) order:任何对象的属性都将以任意(例如随机)顺序迭代:

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

Strictly speaking, even arrays are not guaranteed by the specification to iterate in natural order using a for-in loop;严格来说,即使是 arrays 规范也不能保证使用for-in循环以自然顺序进行迭代; however, most JavaScript interpreters do so anyway.但是,大多数 JavaScript 解释器无论如何都会这样做。 (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. (值得注意的是,IE8 以分配索引的顺序进行迭代,而不是自然顺序。)这就是为什么您应该始终在普通的“for”循环中使用索引来迭代 arrays。

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'...
}

These differences mean that regardless of how your "Fruit" object is defined there is no reliable way to ensure a strict ordering of keys (eg "Banana", "Apple", "Color", "Size", etc.) unless you retain your own ordering separately.这些差异意味着,无论您的“水果”object 是如何定义的,都没有可靠的方法来确保键的严格排序(例如“香蕉”、“苹果”、“颜色”、“尺寸”等),除非您保留您自己单独订购。

You can't , unless you copy your string indexes to numeric indexes, but they would be new elements in your array不能除非您将字符串索引复制到数字索引,但它们将是数组中的新元素

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 object 之间的区别。

An object has properties with keys that are strings, but you can't access those properties with an index integer, only by the key. object 的属性的键是字符串,但您不能使用索引 integer 访问这些属性,只能通过键。

An array is a special type of object that provides array functionality like a length property and some methods like sort() , etc. Array properties are normally assigned with numeric indexes, and the length property is based on those numerically indexed properties, but because arrays are still objects you can also assign properties with string keys.数组是 object 的一种特殊类型,它提供数组功能,如length属性和一些方法,如sort()等。数组属性通常分配有数字索引, length属性基于那些数字索引的属性,但是因为 arrays仍然是对象,您还可以使用字符串键分配属性。 If you say myArray['banana'] =.. that 'banana' property is not accessible via an index number.如果你说myArray['banana'] =.. 'banana' 属性不能通过索引号访问。

If you want keys like 'banana' you shouldn't be using an array at all, just use a plain object.如果您想要像“香蕉”这样的键,则根本不应该使用数组,只需使用普通的 object。

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-considered-harmful/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我如何在不知道Javascript是什么的情况下引用数组的索引? - How do I reference the index of an array without knowing what it is in Javascript? 如何获取数组中项的索引? - How do I get the index of an item in an array? Javascript 如何优化大阵列中的延迟。 它有 350000+ 项 - Javascript how can i do optimize the delay in big array. its have 350000+ item 如何从对象数组及其在JavaScript中的索引中获取最小值? - How do I get the lowest value from an array of objects and its index in JavaScript? Javascript:如何交换对象数组的元素(通过引用而不是索引)? - Javascript: How can I swap elements of an array of objects (by reference, not index)? 如何确定javascript数组中值&gt; 0的最后一项的索引 - How would I determine the index of the last item in javascript array with a value > 0 如何通过索引检查数组对象中的答案? - How do I check answers in array objects by its index? 如何在不知道其索引的情况下删除嵌套数组? - How do I delete a nested array without knowing its index? 如何获取数组项的相反索引和值? - How do I get an Array item's opposite index and value? 如何通过车把中的索引访问访问数组项? - How do I access an access array item by index in handlebars?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM