Filling multidimensional arrays in JavaScript
Suppose now we want to create some multidimensional array with numbers in a loop. For example, here is a two-dimensional array:
javascript[[1, 2, 3], [1, 2, 3], [1, 2, 3]]
Let's solve the problem by using two nested loops. The outer loop will create sub-arrays and the inner loop will fill these sub-arrays with numbers:
javascriptlet arr = [];
for (let i = 0; i < 3; i++) {
arr[i] = []; // create a subarray
for (let j = 0; j < 3; j++) {
arr[i].push(j + 1); // fill the subarray with numbers
}
}
console.log(arr);
Задание 1
Form the following array using two nested loops:
javascript[[1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5]]
Задание 2
Form the following array using two nested loops:
javascript[
['x', 'x', 'x', 'x'],
['x', 'x', 'x', 'x'],
['x', 'x', 'x', 'x']
]
Задание 3
Form the following array using three nested loops:
javascript[
[
[1, 2, 3, 4, 5],
[1, 2, 3, 4, 5],
],
[
[1, 2, 3, 4, 5],
[1, 2, 3, 4, 5],
],
[
[1, 2, 3, 4, 5],
[1, 2, 3, 4, 5],
],
]