push()一个二维数组 [英] push() a two-dimensional array

查看:364
本文介绍了push()一个二维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


$ b

  var我试图把它推到一个二维数组中。 myArray = [
[1,1,1,1,1],
[1,1,1,1,1],
[1,1,1,1,1]
]

我试过的代码是:

  var r = 3; //从行开始3 
var c = 5; //从第5列开始

var rows = 8;
var cols = 7; (var j = c; j< cols; j ++)
{b;



myArray [i] [j] .push(0);




$ b $ p
$ b

这应该导致以下结果:

  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],
]

但是它并不确定这是否是正确的方法。所以问题是我该如何做到这一点?

你的代码中有一些错误:
$ b $ ol
  • 使用 myArray [i] .push(0); 添加一个新的列。你的代码( myArray [i] [j] .push(0); )可以在三维数组中工作,因为它试图在位置上向数组添加另一个元素您只能在所有行中扩展(col-d)列的列,即使在那些列中,它们还没有被初始化,因此目前还没有条目。


    一个正确的,虽然是一种冗长的版本,以下内容:

      var r = 3; //从行开始3 
    var c = 5; //从第5列开始

    var rows = 8;
    var cols = 7;

    //展开为正确的数量或行
    for(var i = r; i< rows; i ++){
    myArray.push([]);


    //展开所有行以获得正确数量的列
    for(var i = 0; i {
    for(var j = myArray [i] .length; j {
    myArray [i] .push(0);
    }
    }


    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]
    ]
    

    And my code I'm trying is:

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

    That should result in the following:

    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:

    1. 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].
    2. 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 c = 5; //start from col 5
    
    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屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆