And an object method for an array traversal Comparative

An array, for example, JavaScript offers a variety of traversal syntax. The most original wording is forcirculating.

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

  

The wording is too much trouble, and therefore provides an array of built-in forEachmethod.

myArray.forEach(function (value) {
  console.log(value);
});

 

The wording of the question that can not be half-way out of the forEachloop, breakthe command or returncommands are not effective.

for...inKeys can traverse the loop array.

for (var index in myArray) {
  console.log(myArray[index]);
}

 

for...inCirculation has several drawbacks.

  • The digital array keys, but the for...incycle is a character string as keys "0", "1", "2" and so on.
  • for...inNot only traversal cycle numeric keys, other keys will be added manually traverse, and even key on the prototype chain.
  • In some cases, for...inthe cycle will traverse the keys in any order.

In short, for...inthe cycle is mainly designed to traverse the object, it does not apply to traverse the array.

for ... of several cycles as compared to the above approach, there are some significant advantages. 

for (value of the let myArray) { 
  console.log (value); 
} 
has the same for ... in the same concise syntax, but not for ... in those drawbacks. 
Unlike forEach method, it may break, continue with the use and return. 
Through all the data structure provides a unified user interface. 
Here's a break statement out for ... Examples of cycles. 

for ( var n-of Fibonacci) {
   IF (n-> 1000 )
     BREAK ; 
  the console.log (n-); 
} 
The above example will be output Fibonacci less item 1000. If the current item is greater than 1000, will be used for ... of the break statement out of the loop.

 

 

Guess you like

Origin www.cnblogs.com/followme789/p/10968875.html