[英]Iterate through multidimensional array javascript
I was wondering how can I get the multidimensional array like [[A1, B1, C1....],[A2, B2, C2....]];我想知道如何获得多维数组,如 [[A1, B1, C1....],[A2, B2, C2....]];
let grid = [ [] ]; let letters = "abcdefghij".toUpperCase(); // create the Grid const createGrid = (size) => { let row = 0; let col = 0; for (row = 0; row < size; row++) { grid[row] = []; for (col = 0; col < letters.length; col++) { grid[row][col] = `${letters[row]}${col + 1}`; } } }; createGrid(letters.length); console.log(grid);
If you don't mind converting your code to ES6+, this one should do the trick.如果您不介意将您的代码转换为 ES6+,那么这个应该可以解决问题。
const letters = "abcdefghij".toUpperCase(); const createGrid = (letters) => Array.from( { length: letters.length }, (_, index) => [...letters].map((letter) => `${letter}${index + 1}`) ); console.log(createGrid(letters));
Just refer the col
instead of the row
and concat the row + 1
to it in the inner loop when you are doing the assignment.在进行分配时,只需在内部循环中引用
col
而不是row
并将row + 1
连接到它。
let grid = [ [] ]; let letters = "abcdefghij".toUpperCase(); // create the Grid const createGrid = (size) => { let row = 0; let col = 0; for (row = 0; row < size; row++) { grid[row] = []; for (col = 0; col < letters.length; col++) { // instead of grid[row][col] = `${letters[row]}${col + 1}`; grid[row][col] = `${letters[col]}${row + 1}`; } } }; createGrid(letters.length); console.log(grid);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.