function zeroArray(m, n) {
// Creates a 2-D array with m rows and n columns of zeroes
let newArray = [];
let row = [];
for (let i = 0; i < m; i++) {
// Adds the m-th row into newArray
for (let j = 0; j < n; j++) {
// Pushes n zeroes into the current row to create the columns
row.push(0);
}
// Pushes the current row, which now has n zeroes in it, to the array
newArray.push(row);
}
return newArray;
}
let matrix = zeroArray(3, 2);
console.log(matrix);
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:79.0) Gecko/20100101 Firefox/79.0.
Challenge: Use Caution When Reinitializing Variables Inside a Loop
let arr = [0,0,0]
let outerArr = [];
outerArr.push(arr)
// outerArr equals [[0,0,0]]
arr[1] = 1;
// arr is equal [0,1,0]
// and outerArr is also equal to [[0,1,0]]
outerArr.push(arr)
// now outerArr is equal [[0,1,0], [0,1,0]]
because arrays work by reference, doing outerArr.push(arr) you are pushing a reference to arr, aby change to arr is reflected in outerArr because outerArr is practically [arr, arr]