This is a brief introduction of 4 ways loop through items in array.
1: for
This is the simplest way. You can modify the i++
to skip some of the array items. eg i+=2
to skip all even items.
let arr=[1,2,3,4]
for(i = 0; i < arr.length; i++) {
console.log(arr[i]); //output:1 2 3 4
}
2: for-in (not recommend)
This method will give you the index(key) of array as string.
You may need to access the item by arr[index]
.
let arr=[1,2,3,4]
for(let index in arr) {
console.log(index); //output:0 1 2 3
console.log(typeof index) //output: string
}
3: forEach
You can pass a function to forEach
:value=>{…}
If you want to modify the items you can pass a function like this: (value,index,array)=>{...}
then access the item by array[index]
let arr=[1,2,3,4]
arr.forEach(value => console.log(value)); //output:1 2 3 4arr.forEach((value,index,array) => array[index]=++value);
console.log(arr) //output:[2 3 4 5]
You may want to use for-of
rather than forEach
if it involves async/await, to learn more, please read my story about async/await with forEach
4: for-of
Similar to for-in, but this method will give you the value of array item.
let arr=[1,2,3,4]
for(let value of arr) {
console.log(index); //output:1 2 3 4
}