Home > front end >  Why does this simple javascript array fail?
Why does this simple javascript array fail?

Time:04-13

I am getting old or just rusty or both, but I hang my head in shame as I bring this here because there must be something really, really simple that I am missing.

I am writing this using Google Apps script in Sheets.

Why does this fail once I reach j = 2? I have tried declaring the array in every different way I can think of, nothing gets past j=2. Wth am I missing? It's something dumb I know it.

function myFailure() {
  for (var j = 0; j < 10; j  ) {
    for (var k = 0; k < 31; k  ) {
      var item = 'Item ' k;
      let thisItem = new Array([],[]);
      thisItem[j][k] = item;  //the problem is happening here, once j=2 but why
      console.log(j,k);
      console.log(thisItem[j][k]);
    }
  }
}

myFailure();

CodePudding user response:

Try this:

function myFailure() {
  let thisItem = [];
  for (var j = 0; j < 10; j  ) {
    thisItem[j] = []
    for (var k = 0; k < 31; k  ) {
      thisItem[j][k] = `Item [${j}][${k}]`
      console.log(thisItem[j][k]);
    }
  }
}

Partial Execution log

10:04:00 AM Info    Item [0][0]
10:04:00 AM Info    Item [0][1]
10:04:00 AM Info    Item [0][2]
10:04:00 AM Info    Item [0][3]
10:04:00 AM Info    Item [0][4]
10:04:00 AM Info    Item [0][5]
  • Related