Loop through an array in JavaScript

2018-12-30 22:49发布

In Java you can use a for loop to traverse objects in an array as follows:

String[] myStringArray = {"Hello", "World"};
for (String s : myStringArray)
{
    // Do something
}

Can you do the same in JavaScript?

30条回答
谁念西风独自凉
2楼-- · 2018-12-30 23:21

You can use map, which is a functional programming technique that's also available in other languages like Python and Haskell.

[1,2,3,4].map( function(item) {
     alert(item);
})

The general syntax is:

array.map(func)

In general func would take one parameter, which is an item of the array. But in the case of JavaScript, it can take a second parameter which is the item's index, and a third parameter which is the array itself.

The return value of array.map is another array, so you can use it like this:

var x = [1,2,3,4].map( function(item) {return item * 10;});

And now x is [10,20,30,40].

You don't have to write the function inline. It could be a separate function.

var item_processor = function(item) {
      // Do something complicated to an item
}

new_list = my_list.map(item_processor);

which would be sort-of equivalent to:

 for (item in my_list) {item_processor(item);}

Except you don't get the new_list.

查看更多
有味是清欢
3楼-- · 2018-12-30 23:21

In JavaScript it's not advisable to loop through an Array with a for-in loop, but it's better using a for loop such as:

for(var i=0, len=myArray.length; i < len; i++){}

It's optimized as well ("caching" the array length). If you'd like to learn more, read my post on the subject.

查看更多
骚的不知所云
4楼-- · 2018-12-30 23:21

I did not yet see this variation, which I personally like the best:

Given an array:

var someArray = ["some", "example", "array"];

You can loop over it without ever accessing the length property:

for (var i=0, item; item=someArray[i]; i++) {
  // item is "some", then "example", then "array"
  // i is the index of item in the array
  alert("someArray[" + i + "]: " + item);
}

See this JsFiddle demonstrating that: http://jsfiddle.net/prvzk/

This only works for arrays that are not sparse. Meaning that there actually is a value at each index in the array. However, I found that in practice I hardly ever use sparse arrays in Javascript... In such cases it's usually a lot easier to use an object as a map/hashtable. If you do have a sparse array, and want to loop over 0 .. length-1, you need the for (var i=0; i<someArray.length; ++i) construct, but you still need an if inside the loop to check whether the element at the current index is actually defined.

Also, as CMS mentions in a comment below, you can only use this on arrays that don't contain any falsish values. The array of strings from the example works, but if you have empty strings, or numbers that are 0 or NaN, etc. the loop will break off prematurely. Again in practice this is hardly ever a problem for me, but it is something to keep in mind, which makes this a loop to think about before you use it... That may disqualify it for some people :)

What I like about this loop is:

  • It's short to write
  • No need to access (let alone cache) the length property
  • The item to access is automatically defined within the loop body under the name you pick.
  • Combines very naturally with array.push and array.splice to use arrays like lists/stacks

The reason this works is that the array specification mandates that when you read an item from an index >= the array's length, it will return undefined. When you write to such a location it will actually update the length.

For me, this construct most closely emulates the Java 5 syntax that I love:

for (String item : someArray) {
}

... with the added benefit of also knowing about the current index inside the loop

查看更多
不流泪的眼
5楼-- · 2018-12-30 23:22

I would thoroughly recommend making use of the underscore.js library. It provides you with various functions that you can use to iterate over arrays/collections.

For instance:

_.each([1, 2, 3], function(num){ alert(num); });
=> alerts each number in turn...
查看更多
初与友歌
6楼-- · 2018-12-30 23:23

It's not 100% identical, but similar:

   var myStringArray = ['Hello', 'World']; // array uses [] not {}
    for (var i in myStringArray) {
        console.log(i + ' -> ' + myStringArray[i]); // i is the index/key, not the item
    }

查看更多
荒废的爱情
7楼-- · 2018-12-30 23:24

for (var s of myStringArray) {

(Directly answering your question: now you can!)

Most other answers are right, but they do not mention (as of this writing) that ECMA Script  6  2015 is bringing a new mechanism for doing iteration, the for..of loop.

This new syntax is the most elegant way to iterate an array in javascript (as long you don't need the iteration index), but it is not yet widely supported by the browsers.

It currently works with Firefox 13+, Chrome 37+ and it does not natively work with other browsers (see browser compatibility below). Luckily we have JS compilers (such as Babel) that allow us to use next-generation features today.

It also works on Node (I tested it on version 0.12.0).

Iterating an array

// You could also use "let" instead of "var" for block scope.
for (var letter of ["a", "b", "c"]) { 
   console.log(letter); 
}

Iterating an array of objects

var band = [
  {firstName : 'John', lastName: 'Lennon'}, 
  {firstName : 'Paul', lastName: 'McCartney'}
];

for(var member of band){
  console.log(member.firstName + ' ' + member.lastName); 
}

Iterating a generator:

(example extracted from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of)

function* fibonacci() { // a generator function
  let [prev, curr] = [1, 1];
  while (true) {
    [prev, curr] = [curr, prev + curr];
    yield curr;
  }
}

for (let n of fibonacci()) {
  console.log(n);
  // truncate the sequence at 1000
  if (n >= 1000) {
    break;
  }
}

Compatibility table: http://kangax.github.io/es5-compat-table/es6/#For..of loops

Spec: http://wiki.ecmascript.org/doku.php?id=harmony:iterators

}

查看更多
登录 后发表回答