简体   繁体   中英

Access parent index in the child element in nested foreach in javascript

 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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM