An array, for example, JavaScript offers a variety of traversal syntax. The most original wording of a for loop.
for (var index = 0; index < myArray.length; index++) { console.log(myArray[index]); }
Such an approach much trouble, thus providing an array built ES5 forEach method.
myArray.forEach(function (value) { console.log(value); });
The wording of the question that can not be half-way out of forEach loop, break command does not return statement in the function can return from closure.
for ... in loop can iterate over the keys of the array.
for (var index in myArray) {// Do not do the actual code the console.log (the myArray [index]); }
for ... in loop has several drawbacks.
- An array of key names are digital, but for ... in loop is the key name as a string of "0", "1", "2" and so on. If you use a string index to participate in certain operations ( "2" + 1 == "21"), the operational results may not meet expectations.
- for ... in loop to traverse not only numeric keys, other keys will be added manually traverse, and even key on the prototype chain.
- In some cases, for ... in loop will traverse the keys in any order.
- In short, for ... in the main loop is 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 (let value of myArray) { console.log(value); }
- Like there for ... in simple 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.
The following is a break statement, for ... example out of circulation.
for (var n of fibonacci) { if (n > 1000) break; console.log(n); }
The above example will output the Fibonacci sequence of 1,000 or less entries. If the current item is greater than 1000, will be used for ... of the break statement out of the loop.