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

12,453

Solution 1

It looks like you are confusing JavaScript array objects with the fact that all objects 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.

Any object's properties will be iterated in arbitrary (e.g. 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 (e.g. "Banana", "Apple", "Color", "Size", etc.) unless you retain your own ordering separately.

Solution 2

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

Solution 3

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

Share:
12,453
Craig
Author by

Craig

Updated on June 05, 2022

Comments

  • Craig
    Craig almost 2 years

    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? e.g.

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