[JS] Update answer about ways to iterate arrays (#149)
* Add for-of loop as an another way to iterate arrays * Update javascript-questions.md
This commit is contained in:
parent
676c8d99de
commit
c50fcd2dd2
|
|
@ -838,8 +838,24 @@ For arrays:
|
|||
|
||||
* `for` loops - `for (var i = 0; i < arr.length; i++)`. The common pitfall here is that `var` is in the function scope and not the block scope and most of the time you would want block scoped iterator variable. ES2015 introduces `let` which has block scope and it is recommended to use that instead. So this becomes: `for (let i = 0; i < arr.length; i++)`.
|
||||
* `forEach` - `arr.forEach(function (el, index) { ... })`. This construct can be more convenient at times because you do not have to use the `index` if all you need is the array elements. There are also the `every` and `some` methods which will allow you to terminate the iteration early.
|
||||
* `for-of` loops - `for (let elem of arr) { ... }`. ES6 introduces a new loop, the `for-of` loop, that allows you to loop over objects that conform to the [iterable protocol](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol) such as `String`, `Array`, `Map`, `Set`, etc. It combines the advantages of the `for` loop and the `forEach()` method. The advantage of the `for-of` loop is that you can break from it, and the advantage of `forEach()` is that it is more concise than the `for` loop because you don't need a counter variable. With the `for-of` loop, you get both the ability to break from a loop and a more concise syntax.
|
||||
|
||||
Most of the time, I would prefer the `.forEach` method, but it really depends on what you are trying to do. `for` loops allow more flexibility, such as prematurely terminate the loop using `break` or incrementing the iterator more than once per loop.
|
||||
Most of the time, I would prefer the `.forEach` method, but it really depends on what you are trying to do. Before ES6, we used `for` loops when we needed to prematurely terminate the loop using `break`. But now with ES6, we can do that with `for-of` loops. I would use `for` loops when I need even more flexibility, such as incrementing the iterator more than once per loop.
|
||||
|
||||
Also, when using the `for-of` loop, if you need to access both the index and value of each array element, you can do so with the ES6 Array `entries()` method and destructuring:
|
||||
|
||||
```
|
||||
const arr = ['a', 'b', 'c'];
|
||||
|
||||
for (let [index, elem] of arr.entries()) {
|
||||
console.log(index, ': ', elem);
|
||||
}
|
||||
```
|
||||
|
||||
###### References
|
||||
|
||||
- http://2ality.com/2015/08/getting-started-es6.html#from-for-to-foreach-to-for-of
|
||||
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/entries
|
||||
|
||||
[[↑] Back to top](#js-questions)
|
||||
|
||||
|
|
|
|||
Loading…
Reference in New Issue