Forum Moderators: open
Say i have the following array:
arr[53] = "apples";
arr[27] = "oranges";
arr[38] = "lemons";
And I want to loop through each element of the array and get the key and the Value?
I would do:
for(i=0;i<arr.length;i++){
//How would i echo the key/value at this point?
}
Thanks!
Ryan
In your example, you're going to have an array that contains at least 54 items (your highest index is 53, and JavaScript arrays are zero indexed). If you do something like this:
for( var i = 0; i < arr.length; i++) {
alert("arr[" + i + "] = " + arr[i]);
}
Then arr.length is going to be 54, i represents the index, and arr[i] will get the value. In this case, if you've only populated 3 values in the array, you're going to be looping through a bunch of 'undefined' values.
I did find another usefull method.
for(var i in arr) {
alert(i+" is "+arr[i]);
}
var arr = [
{id : 53, fruit: "apples"},
{id : 27, fruit: "oranges"},
{id : 38, fruit: "lemons"}
];
for (var i = 0; i < arr.length; i++) {
alert(arr[i].fruit + " has an id of " + arr[i].id);
}
This treats the contents of the array as objects.