1

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();

3
  • 1
    console.log(thisItem) and I think this will point you out to the solution ;) Commented Apr 12, 2022 at 15:35
  • 7
    new Array([], []) creates an array with 2 arrays in it. When j is 0 or 1, it works, but not when it's 2. Commented Apr 12, 2022 at 15:35
  • 1
    In general it's better to use the myArray = [] format instead of new Array(). Check out this answer as a reference. Commented Apr 12, 2022 at 17:13

1 Answer 1

2

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]
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I see the issue now. I was bunching up my array in the loop.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.