ref – https://stackoverflow.com/questions/5349425/whats-the-fastest-way-to-loop-through-an-array-in-javascript
given array
1 |
let ArrPerson = ["ricky", "david", "james"]; |
filter
1 2 3 4 |
console.log("---filter---"); ArrPerson.filter(function(item, index) { console.log(`${item}, ${index}`); }); |
forEach
1 2 3 4 |
console.log("---forEach---"); ArrPerson.forEach(function(key, value){ console.log(`${key}, ${value}`) }); |
map
warning: map is for generating a new array, we manipulate each element, and the function generates a new array with those new changes.
Its purpose is not really for iterating an array. For completeness, it is included.
1 2 3 |
ArrPerson.map( function(item, index) { console.log(`item - ${item}, index - ${index}`); }); |
for loop
1 2 3 |
for (let i = 0; i < ArrPerson.length; i++) { console.log(`${ArrPerson[i]}, ${i}`); } |
while loop
1 2 3 4 5 |
var len = ArrPerson.length; let j = 0; while ((len--) > 0) { console.log(`${ArrPerson[j++]}`) } |