views:

538

answers:

3

I have an array in Javascript:

var array = new array();
array[0] = "apples";
array[1] = "oranges";
array[2] = "pears";

In PHP, with a given array, I can use the following to loop through an array, and break up the keys and values:

foreach ($array as $key => $value) {
    echo("Key is $key and Value is $value");
}

How can I do this in Javascript? I'm aware of:

for (x in array){
    // Do something with x.
}

But I've found nothing that will replicate the php style foreach. Is it possible to concisely achieve something similar in Javascript? (I'm also using jQuery, if something can be done in jQuery).

+8  A: 

First,

var array=[];

is preferable to using "new."

Second, your keys are numeric in this case, so you just do:

for (i=0;i<array.length;i++) {
  console.log("Key is "+i+" and Value is "+array[i]);
}

If you want to have keys that aren't numeric, use a JavaScript object instead of an array. It's valid to use strings instead of numbers as array indexes, but JavaScript doesn't have much support for that.


I use "console.log" because I assume you don't want a bunch of alerts popping up. console.log could be replaced with whatever you use to log info. You could use alert() or write text into a div instead.

Nosredna
You should add that console.log requires firefox with firebug.
ichiban
@ichiban. Good point. I edited my answer to mention that.
Nosredna
The answer is to use Javascript Objects then - as it would appear I require something a bit more flexible than the standard array. (My arrays are generated dynamically, and do contain values that are not numeric). Thanks for answering.
EvilChookie
Also thanks for the info regarding the new array declaration. Will keep that in mind.
EvilChookie
OK. Remember that you CAN do array["one"]="apples" and then use for-in, but it's considered weird in JavaScript to do that, and others might be baffled by your code.
Nosredna
Also, the for...in syntax is really slow if you end up with a large array - there was a Google tech talk on it recently.
robertc
Nosredna
Console.log doesn't require Firebug. It also works with Safari's debugger.
alex
A: 

If order isn't a priority (or even if it is, you could always just reverse the array), here's my preferred method:

var i = array.length;
while(i--) {
  console.log("key is " + i + " and value is " + array[i]);
}

This approach works because the number 0 evaluates as false in JavaScript.

nakajima
+5  A: 

Using jQuery.each you could write something similar to (not tested):

jQuery.each(array, function(k,v) {
    console.log("K: "+,k," V:",v);
});
Grzegorz Oledzki
Except this would require jQuery...
musicfreak
as requested in the question.
SilentGhost