我及时写了一些C#代码,现在我正在尝试在Javascript中做同样的事情,但我对创建二维数组感到困惑,如果有可能创建新对象并将其推入2D数组?
我在C#中的表现如何:
gameGrid[column][row] = new ColorObject(x,y,color);
然后从这样的方法中获取值:
gameGrid[1][2].showColor;
是否可以在这样的Javascript中添加推送对象,还是有其他选项?
gameGrid[col][row].push(new ColorObject(x,y,color));
答案 0 :(得分:2)
假设你的gameGrid是一个数组数组,那你只需:
gameGrid[c][r] = new ColorObject(x,y,color);
var gameGrid = [];
var cols = 10;
var rows = 10;
for (var c=0; c<cols; c++) {
gameGrid.push([]);
for (var r=0; r<rows; r++) {
gameGrid[c][r] = new ColorObject(x,y,color);
}
}
javascript中的 push
是Array对象的一种方法,如果你想使用它,它就变成了:
for (var c=0; c<cols; c++) {
gameGrid.push([]);
for (var r=0; r<rows; r++) {
gameGrid[c].push(new ColorObject(x,y,color));
}
}
答案 1 :(得分:1)
在C#中,您可能会执行以下操作:
ColorObject[][] gameGrid = new ColorObject[10][];
for(int i = 0; i < 10; i++)
{
gameGrid[i] = new ColorObject[10];
for(int j = 0; j < 10; j++)
{
gameGrid[i][j] = new ColorObject(i, j, someValue);
}
}
嗯,这几乎与JavaScript相同:
var gameGrid = new Array(10); // or "= [];" and then push instead of "gameGrid[i] = ..."
for(var i = 0; i < 10; i++) {
gameGrid[i] = new Array(10); // or "[]" and then push instead of "gameGrid[i][j] = ..."
for(var j = 0; j < 10; j++) {
gameGrid[i][j] = new ColorObject(i, j, someValue);
}
}
之后,您可以像在C#中一样访问10 x 10d阵列:
gameGrid[row][col] = new ColorObject(x, y, color);
gameGrid[1][2].showColor();