push() 一个二维数组 [英] push() a two-dimensional array
本文介绍了push() 一个二维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试推送到一个二维数组而不会弄乱,目前我的数组是:
I'm trying to push to a two-dimensional array without it messing up, currently My array is:
var myArray = [
[1,1,1,1,1],
[1,1,1,1,1],
[1,1,1,1,1]
]
我正在尝试的代码是:
var r = 3; //start from rows 3
var c = 5; //start from col 5
var rows = 8;
var cols = 7;
for (var i = r; i < rows; i++)
{
for (var j = c; j < cols; j++)
{
myArray[i][j].push(0);
}
}
结果如下:
var myArray = [
[1,1,1,1,1,0,0],
[1,1,1,1,1,0,0],
[1,1,1,1,1,0,0],
[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0],
]
但它并不确定这是否是正确的方法.
But it doesn't and not sure whether this is the correct way to do it or not.
那么问题是我将如何实现这一点?
So the question is how would I accomplish this?
推荐答案
您的代码中有一些错误:
You have some errors in your code:
- 使用
myArray[i].push( 0 );
添加新列.您的代码 (myArray[i][j].push(0);
) 将在 3 维数组中工作,因为它会尝试将另一个元素添加到位于[i] 位置的数组中[j]
. - 您只在所有行中扩展 (col-d)-许多列,即使在那些尚未初始化并因此到目前为止没有条目的列中也是如此.
- Use
myArray[i].push( 0 );
to add a new column. Your code (myArray[i][j].push(0);
) would work in a 3-dimensional array as it tries to add another element to an array at position[i][j]
. - You only expand (col-d)-many columns in all rows, even in those, which haven't been initialized yet and thus have no entries so far.
一个正确的,虽然有点冗长的版本,如下:
One correct, although kind of verbose version, would be the following:
var r = 3; //start from rows 3
var rows = 8;
var cols = 7;
// expand to have the correct amount or rows
for( var i=r; i<rows; i++ ) {
myArray.push( [] );
}
// expand all rows to have the correct amount of cols
for (var i = 0; i < rows; i++)
{
for (var j = myArray[i].length; j < cols; j++)
{
myArray[i].push(0);
}
}
这篇关于push() 一个二维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文