Loop through an array in JavaScript

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?


Use a sequential for loop:

var myStringArray = ["Hello","World"];
var arrayLength = myStringArray.length;
for (var i = 0; i < arrayLength; i++) {
    alert(myStringArray[i]);
    //Do something
}

@zipcodeman suggests the use of the for...in statement, but for iterating arrays for-in should be avoided, that statement is meant to enumerate object properties.

It shouldn't be used for array-like objects because:

  • The order of iteration is not guaranteed, the array indexes may not be visited in numeric order.
  • Inherited properties are also enumerated.
  • The second point is that it can give you a lot of problems, for example, if you extend the Array.prototype object to include a method there, that property will be also enumerated.

    For example:

    Array.prototype.foo = "foo!";
    var array = ['a', 'b', 'c'];
    
    for (var i in array) {
      alert(array[i]);
    }
    

    The above code will alert, "a", "b", "c" and "foo!".

    That be particularly a problem if you use some library that relies heavily on native prototypes augmention (such as MooTools for example).

    The for-in statement as I said before is there to enumerate object properties, for example:

    var obj = {
      "a": 1,
      "b": 2,
      "c": 3
    };
    
    for (var prop in obj) {
      if (obj.hasOwnProperty(prop)) { 
      // or if (Object.prototype.hasOwnProperty.call(obj,prop)) for safety...
        alert("prop: " + prop + " value: " + obj[prop])
      }
    }
    

    In the above example the hasOwnProperty method allows you to enumerate only own properties, that's it, only the properties that the object physically has, no inherited properties.

    I would recommend you to read the following article:

  • Enumeration VS Iteration

  • Yes, but only if your implementation includes the for ... of feature introduced in ECMAScript 2015 (the "Harmony" release).

    It works like this:

    // REQUIRES ECMASCRIPT 2015+
    var s, myStringArray = ["Hello", "World"];
    for (s of myStringArray) {
      // ... do something with s ...
    }
    

    Or better yet, since ECMAScript 2015 also provides block-scoped variables via let and const :

    // REQUIRES ECMASCRIPT 2015+
    const myStringArray = ["Hello", "World"];
    for (let s of myStringArray) {
      // ... do something with s ...
    }
    // s is no longer defined here
    

    Many JavaScript developers are still working in an environment that's not there yet, however - especially if writing code to run in web browsers, where the site developers often can't be sure what browser/version their clients will be using.

    If you can assume the JavaScript interpreter is compliant with the previous edition of the ECMAScript specification (which rules out, for example, versions of Internet Explorer before 9), then you can use the forEach iterator method instead of a loop. In that case, you pass a function to be called on each item in the array:

    var myStringArray = [ "Hello", "World" ];
    myStringArray.forEach( function(s) { 
         // ... do something with s ...
    } );
    

    But if even that is too much to assume, and you want something that works in all versions of JavaScript, then you have to use an explicit counting loop. The safest version, which handles sparse arrays properly, is something like this:

    var i, s, myStringArray = [ "Hello", "World" ], len = myStringArray.length;
    for (i=0; i<len; ++i) {
      if (i in myStringArray) {
        s = myStringArray[i];
        // ... do something with s ...
      }
    }
    

    Assigning the length value to the local variable (as opposed to including the full myStringArray.length expression in the loop condition) can make a significant difference in performance since it skips a property lookup each time through; using Rhino on my machine, the speedup is 43%.

    You will often see the length caching done in the loop initialization clause, like this:

    var i, len, myStringArray = [ "Hello", "World" ];
    for (len = myStringArray.length, i=0; i<len; ++i) {
    

    The for ... in syntax mentioned by others is for looping over an object's properties; since an Array in JavaScript is just an object with numeric property names (and an automatically-updated length property), you can theoretically loop over an Array with it. But the problem is that it doesn't restrict itself to the numeric property values (remember that even methods are actually just properties whose value is a closure), nor does it iterate over those in numeric order. Therefore, the for ... in syntax should not be used for looping through Arrays.


    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 .

    链接地址: http://www.djcxy.com/p/612.html

    上一篇: 显式关键字是什么意思?

    下一篇: 在JavaScript中循环访问数组