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:39

There are a couple of ways to do it in JavaScript. The first two examples are JavaScript samples. The third one makes use of a JavaScript library, that is, jQuery making use of the .each() function.

var myStringArray = ["hello", "World"];
for(var i in myStringArray) {
  alert(myStringArray[i]);
}

var myStringArray = ["hello", "World"];
for (var i=0; i < myStringArray.length; i++) {
  alert(myStringArray[i]);
}

var myStringArray = ["hello", "World"];
$.each(myStringArray, function(index, value){
  alert(value);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

查看更多
倾城一夜雪
3楼-- · 2018-12-30 23:42

In JavaScript, there are so many solutions to loop an array.

The code below are popular ones

/** Declare inputs */
const items = ['Hello', 'World']

/** Solution 1. Simple for */
console.log('solution 1. simple for')

for (let i = 0; i < items.length; i++) {
  console.log(items[i])
}

console.log()
console.log()

/** Solution 2. Simple while */
console.log('solution 2. simple while')

let i = 0
while (i < items.length) {
  console.log(items[i++])
}

console.log()
console.log()

/** Solution 3. forEach*/
console.log('solution 3. forEach')

items.forEach(item => {
  console.log(item)
})

console.log()
console.log()

/** Solution 4. for-of*/
console.log('solution 4. for-of')

for (const item of items) {
  console.log(item)
}

console.log()
console.log()

查看更多
裙下三千臣
4楼-- · 2018-12-30 23:45

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:

查看更多
倾城一夜雪
5楼-- · 2018-12-30 23:46

There is a way to do it where you have very little implicit scope in your loop and do away with extra variables.

var i = 0,
     item;

// note this is weak to sparse arrays or falsey values
for ( ; item = myStringArray[i++] ; ){ 
    item; // This is the string at the index.
}

Or if you really want to get the id and have a really classical for loop:

var i = 0,
    len = myStringArray.length; // cache the length

for ( ; i < len ; i++ ){
    myStringArray[i]; // Don't use this if you plan on changing the length of the array
}

Modern browsers all support iterator methods forEach, map, reduce, filter and a host of other methods on the Array prototype.

查看更多
一个人的天荒地老
6楼-- · 2018-12-30 23:46

There's a method to iterate over only own object properties, not including prototype's ones:

for (var i in array) if (array.hasOwnProperty(i)) {
    // do something with array[i]
}

but it still will iterate over custom-defined properties.

In javascript any custom property could be assigned to any object including array.

If one wants to iterate over sparsed array, for (var i = 0; i < array.length; i++) if (i in array) or array.forEach with es5shim should be used.

查看更多
皆成旧梦
7楼-- · 2018-12-30 23:46

Short answer: yes. You can do with this:

var myArray = ["element1", "element2", "element3", "element4"];

for (i = 0; i < myArray.length; i++) {
  console.log(myArray[i]);
}

In a browser console, you can see something like "element1", "element2", etc., printed.

查看更多
登录 后发表回答