Take the following function to generate a square multiplication table:
function getMultTable(n) {
/* generate multiplication table from 1 to n */
let table = new Array(n);
for (let i=1; i<=n; i++) {
table[i-1] = new Array(n);
for (let j=1; j<=n; j++) {
table[i-1][j-1] = i*j;
}
}
return table;
}
console.log(getMultTable(3));
// [
// [ 1, 2, 3 ],
// [ 2, 4, 6 ],
// [ 3, 6, 9 ]
// ]
Why can't the following be done instead?
function getMultTable(n) {
let table = new Array(n);
for (let i=1; i<=n; i++) {
for (let j=1; j<=n; j++) {
table[i-1][j-1] = i*j;
}
}
return table;
}
In other words, why can't a multi-dimensional array be created on-the-fly in javascript, or is it possible to do that some other way?