Loop through an array in JavaScript

Posted Chuck Lu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Loop through an array in JavaScript相关的知识,希望对你有一定的参考价值。

https://stackoverflow.com/questions/3010840/loop-through-an-array-in-javascript?page=1&tab=votes#tab-top

答案1

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:

 

 

答案2

https://stackoverflow.com/questions/3010840/loop-through-an-array-in-javascript?page=2&tab=votes#tab-top

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

The map() method creates a new array with the results of calling a provided function on every element in the calling array.

arr = ["table", "chair"];

// solution
arr.map((e) => {
  console.log(e);
  return e;
});

以上是关于Loop through an array in JavaScript的主要内容,如果未能解决你的问题,请参考以下文章

csharp 来自https://stackoverflow.com/questions/874380/wpf-how-do-i-loop-through-the-all-controls-in-a-

Paging through lots of data efficiently (and in an Ajax way) with ASP.NET 2.0

解决错误 an't connect to local MySQL server through socket '/usr/local/zend/mysql/tmp/mysql.sock' (2) in

You may have an infinite update loop in a component render function

[Vue warn]: You may have an infinite update loop in a component render function

Search an Element in an array