There are several ways for iterating over arrays. The traditional way is using for and while loop, we can use forEach loop and ES6 has introduced for-of loop also.
Using ES5
Observe below code, we are following traditional approach here
var arr = ['a', 'b', 'c']; for (var i=0; i<arr.length; i++) { var elem = arr[i]; console.log(elem); }
Variable i is available in global scope. Use let keyword instead of var to avoid polluting global scope
ES5 provides forEach loop also. Observe below code. It will pass value to different function
var arr = ['a', 'b', 'c']; arr.forEach(function (elem) { console.log(elem); });
ES5 provides for-in loop also. You can work with indexes
var arr = ['a', 'b', 'c']; for (var i in arr) { console.log(i+' '+arr[i]); }Click here to see DEMO
Using ES6
Observe below for-of loop. Constant elem holds element in array.
const arr = ['a', 'b', 'c']; for (const elem of arr) { console.log(elem); }
If you want to work with indexes too, then use new Array method entries()
const arr = ['a', 'b', 'c']; for (const [index, elem] of arr.entries()) { console.log(index+'. '+elem); }
0 comments:
Post a Comment