简体   繁体   中英

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

I have a JavaScript array:

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/

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 :

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.

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. 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 . 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). Essentially, an Array is just an object with a special "length" property that stores the last integer index (starting from zero) plus one.

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

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.

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.

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 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. If you say myArray['banana'] =.. that 'banana' property is not accessible via an index number.

If you want keys like 'banana' you shouldn't be using an array at all, just use a plain 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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM