-1

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?

David542
  • 104,438
  • 178
  • 489
  • 842
  • Does this answer your question? [How to create multidimensional array](https://stackoverflow.com/questions/7545641/how-to-create-multidimensional-array) – fynmnx Mar 22 '22 at 19:52
  • _"Why can't the following be done instead?"_: you would have to ask the people who write JavaScript specs/engines that question. The simple answer is "because that's how it works". – Andy Mar 22 '22 at 19:59
  • 1
    In that version, when you try `table[i-1][j-1] = i*j`, you are saying, in essence, "fetch the `i-1` property of `table`, and on the resulting value, set the `j-1` property to `i*j`. But the `i-1` property of `table` doesn't exist, so we can't set any property on it. And there is no way the JS engine can read your mind to know that you want that missing value to be a new empty array, instead of an Object, a Rectangle, a Date, or a FooBar. – Scott Sauyet Mar 22 '22 at 20:06

2 Answers2

3

Let's start from the basics, why you can't do the following

let arr;
arr[0] = 1

The answer is because arr is undefined. Well, when an array is initialized it is initialized with all its entries undefined. The operation table[i-1][j-1] = i*j is equivalent to

const row = table[i-1];
row[j-1] = i*j

So, when the table is created all its items are undefined, and the statement row[j-1] = i*j, is trying to set a property of row, in other words setting a property of undefined.

The reason is similar to why you can't run this

function getMultTable(n) {
    let table;
    for (let i=1; i<=n; i++) {
        for (let j=1; j<=n; j++) {
            table[i-1][j-1] = i*j;
        }
    }
    return table;
}

Only that in this case your problem is trying to read a property from undefined

Bob
  • 13,867
  • 1
  • 5
  • 27
1

You can do it something like this:

let arr = new Array(n).fill().map(el => new Array(n).fill());
Sean
  • 1,368
  • 2
  • 9
  • 21