简体   繁体   中英

Looping through elements of an array in Javascript

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

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.

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

jQuery.each(array, function(k,v) {
    console.log("K: "+,k," V:",v);
});

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, eg 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.

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

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.

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

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