9

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

EvilChookie
  • 563
  • 3
  • 14
  • 31

6 Answers6

15

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
  • 83,000
  • 15
  • 95
  • 122
  • 3
    You should add that console.log requires firefox with firebug. – ichiban Jul 14 '09 at 22:29
  • @ichiban. Good point. I edited my answer to mention that. – Nosredna Jul 14 '09 at 22:32
  • 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 Jul 14 '09 at 22:34
  • Also thanks for the info regarding the new array declaration. Will keep that in mind. – EvilChookie Jul 14 '09 at 22:35
  • 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 Jul 14 '09 at 22:39
  • 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 Jul 14 '09 at 22:45
  • @robertc. Yes, you're probably referring to http://www.youtube.com/watch?v=mHtdZgou0qU&feature=channel_page – Nosredna Jul 14 '09 at 22:47
  • Console.log doesn't require Firebug. It also works with Safari's debugger. – alex Jul 14 '09 at 22:56
  • @ichiban: does anybody asking a JS question not know what console.log is? console.log also works in Chrome and IE, with the developer tools. – Ruan Mendes Jun 11 '11 at 00:52
10

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
  • 23,614
  • 16
  • 68
  • 106
2

Have a look at underscorejs.org - with it you do it this way:

_.each(array, function(element, index, array) {
    doSomething(item, index);
});

It is used by backbonejs and many other frameworks/libraries, like meteor, e.g. It has 80 or so extremely useful functions - if you are serious about javascript, take 30 min to read the whole underscore page, you will never want to code in anything but javascript.

esp
  • 7,314
  • 6
  • 49
  • 79
2
for (x in array){

     var arrayItem = array[x]

}

This type of for loop does work, but gives the array position rather than the item from the array itself. It is quite concise and I use it all the time

Taryn
  • 242,637
  • 56
  • 362
  • 405
fkerrigan
  • 270
  • 2
  • 9
0

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
  • 1,862
  • 12
  • 12
0

jQuery is not needed for this kind of task, it can just use a for loop that it's advisable way to loop through an Array in JS. You can read this link text for more detailed info

sebarmeli
  • 17,949
  • 7
  • 35
  • 40