EN
JavaScript - foreach array of arrays
0 points
In this article, we would like to show you how to use a nested for-each loop to iterate an array of arrays in JavaScript.
This section shows how to use forEach
method to iterate over an array of arrays.
xxxxxxxxxx
1
let array = [['item 1', 'item 2'],['item 3', 'item 4']];
2
3
array.forEach((child) => {
4
child.forEach((item, index) => {
5
console.log('child index ' + index + ': ' + item);
6
})
7
});
Note:
Array.prototype.forEach
method was introduced in ES5 (ECMAScript 2009).
This section shows how to use for-of
loop construction to iterate over an array of arrays.
xxxxxxxxxx
1
let array = [['item 1', 'item 2'],['item 3', 'item 4']];
2
3
for(let child of array) {
4
for(let item of child){
5
console.log(item);
6
}
7
}
Note:
for-of
loop was introduced in ES6 (ECMAScript 2015).
This section shows how to use for-in
loop construction to iterate over an array of arrays.
xxxxxxxxxx
1
let array = [['item 1', 'item 2'],['item 3', 'item 4']];
2
3
for(var key1 in array) {
4
if(array.hasOwnProperty(key1)) {
5
let child = array[key1];
6
for(var key2 in child) {
7
if(child.hasOwnProperty(key2)) {
8
console.log(child[key2]);
9
}
10
}
11
}
12
}
Note: using
for-in
loop with array is risky because of possible additional array properties -array.hasOwnProperty(key)
method solves the problem.