[英]How to create a 2d array with array of objects inside columns in javascript?
I want to predefine the 2d-array containing an array of objects like this below image:我想预定义包含对象数组的二维数组,如下图所示:
I am trying this way:我正在尝试这种方式:
var grid = [];
iMax = 3;
jMax = 2;
count = 0;
for (let i = 0; i < iMax; i++) {
grid[i] = [];
for (let j = 0; j < jMax; j++) {
grid[i][j] = count;
count++;
}
}
In your code you're building up the two-dimensional array, but you are filling the rows with numbers
(ie your setting the count
) instead of an array of objects.在您的代码中,您正在构建二维数组,但您正在用numbers
填充行(即设置count
)而不是对象数组。 So if you want to achieve the exact same structure as provided in the screenshot, you can do:因此,如果您想实现与屏幕截图中提供的完全相同的结构,您可以执行以下操作:
const rows = 4; const cols = 4; const elementCount = 3; function buildGrid(rows,cols, elementCount) { const grid = []; for(let i=0; i < rows; i++) { grid[i] = []; for(let j=0; j < cols; j++) { grid[i].push(Array.from({length:elementCount}, () => ({}))); } } return grid; } const grid = buildGrid(rows,cols,elementCount); console.log(grid);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.