1

var game_board = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9],
];

(function plot() {
  game_board.forEach((element, i) => {
    element.forEach((value, j) => {
      // access i here
      console.log(j);
    });
  });
})()

I have a multidimensional array and I want to access both indexes i and j.

4
  • // access i here you should be able to access i there. Try console.log(i, j) and you'll see both indexes Commented Apr 5, 2020 at 4:26
  • Second loop is inside the first loop so i is accessible there were you want it Commented Apr 5, 2020 at 4:28
  • You can access i inside element foreach loop. Commented Apr 5, 2020 at 4:29
  • What is the problem you're facing ? did you tried accessing i ? Commented Apr 5, 2020 at 4:31

2 Answers 2

1

Actually You have access:

var game_board = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9],
];

game_board.forEach((element, i) => {
    element.forEach((value, j) => {
      console.log('i : '+i+', j : '+j);
    });
  });

Note: function arguments of parent function is accessible by child function wherever the nested positions are. So, foreach callback function behaves in the same way.

Sign up to request clarification or add additional context in comments.

Comments

1

Just for illustration:

var game_board = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9],
];

function plot() {
  game_board.forEach((element, i) => {
    element.forEach((value, j) => {
      // access i here
      console.log(j, i);
    });
  });
}

plot();

Comments

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.