推()的二维阵列用JavaScript [英] push() a two-dimensional array with JavaScript

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

问题描述

我试图推到一个二维数组没有它搞乱了,目前我的数组是:

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

和我的code我想的是:

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

这应该导致以下内容:

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?

感谢。

推荐答案

您在你的code一些错误:

You have some errors in your code:


  1. 使用 myArray的[I] .push(0); 来添加新列。您code( myArray的[I] [J] .push(0); )的3维数组来完成工作,因为它试图另一个元素添加到数组在位置 [I] [J]

  2. 您不仅扩大(COL-D)中的所有行-many列,即使在那些,这还没有被初始化,因此没有条目为止。

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

这篇关于推()的二维阵列用JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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