在Javascript中声明一个空的二维数组?

时间:2021-12-10 21:36:08

I want to create a two dimensional array in Javascript where I'm going to store coordinates (x,y). I don't know yet how many pairs of coordinates I will have because they will be dynamically generated by user input.

我想在Javascript中创建一个二维数组,在这里我要存储坐标(x,y)我还不知道有多少对坐标,因为它们是由用户输入动态生成的。

Example of pre-defined 2d array:

预定义2d数组示例:

var Arr=[[1,2],[3,4],[5,6]];

I guess I can use the PUSH method to add a new record at the end of the array.

我想我可以使用PUSH方法在数组的末尾添加一个新的记录。

How do I declare an empty two dimensional array so that when I use my first Arr.push() it will be added to the index 0, and every next record written by push will take the next index?

如何声明一个空的二维数组,以便当我使用第一个Arr.push()时,它将被添加到索引0中,而push写的下一个记录将获取下一个索引?

This is probably very easy to do, I'm just a newbie with JS, and I would appreciate if someone could write a short working code snippet that I could examine. Thanks

这可能很容易做到,我只是一个使用JS的新手,如果有人能写一个我可以检查的简短的工作代码片段,我将不胜感激。谢谢

8 个解决方案

#1


54  

You can just declare a regular array like so:

可以声明一个常规数组,如下所示:

var arry = [];

Then when you have a pair of values to add to the array, all you need to do is:

然后,当您有一对值添加到数组中时,您需要做的就是:

arry.push([value_1, value2]);

And yes, the first time you call arry.push, the pair of values will be placed at index 0.

是的,你第一次给arry打电话。push,这对值将被放置在索引0处。

From the nodejs repl:

从nodejs repl:

> var arry = [];
undefined
> arry.push([1,2]);
1
> arry
[ [ 1, 2 ] ]
> arry.push([2,3]);
2
> arry
[ [ 1, 2 ], [ 2, 3 ] ]

Of course, since javascript is dynamically typed, there will be no type checker enforcing that the array remains 2 dimensional. You will have to make sure to only add pairs of coordinates and not do the following:

当然,由于javascript是动态类型化的,因此没有类型检查器强制要求数组保持二维。您必须确保只添加对的坐标,而不做以下工作:

> arry.push(100);
3
> arry
[ [ 1, 2 ],
  [ 2, 3 ],
  100 ]

#2


15  

If you want to be able access the matrix like so matrix[i][j]

如果你想像这样访问矩阵[i][j]

I find it the most convinient to init it in a loop.

我发现在循环中初始化它是最方便的。

var matrix = [],
    cols = 3;

//init the grid matrix
for ( var i = 0; i < cols; i++ ) {
    matrix[i] = []; 
}

this will give you [ [], [], [] ]

这将给你[],[],[]

so matrix[0][0] matrix[1][0] return undefined and not the error "Uncaught TypeError: Cannot set property '0' of undefined"

因此,矩阵[0][0]矩阵[1][0]返回未定义的,而不是错误“未捕获的类型错误:不能设置未定义的属性‘0’”

#3


4  

An empty array is defined by omitting values, like so:

空数组的定义是省略值,如下所示:

v=[[],[]]
a=[]
b=[1,2]
a.push(b)
b==a[0]

#4


4  

You can nest one array within another using the shorthand syntax:

您可以使用速记语法将一个数组嵌套到另一个数组中:

   var twoDee = [[]];

#5


1  

You can try something like this:-

你可以试试这个:-。

var arr = new Array([]);

Push data:

推动数据:

arr[0][0] = 'abc xyz';

#6


1  

What's wrong with

有什么问题

var arr2 = new Array(10,20);
    arr2[0,0] = 5;
    arr2[0,1] = 2
    console.log("sum is   " + (arr2[0,0] +  arr2[0,1]))

should read out "sum is 7"

应该读出"sum is 7"

#7


1  

You can fill an array with arrays using a function:

你可以用一个函数来填充数组:

var arr = [];
var rows = 11;
var columns = 12;

fill2DimensionsArray(arr, rows, columns);

function fill2DimensionsArray(arr, rows, columns){
    for (var i = 0; i < rows; i++) {
        arr.push([0])
        for (var j = 0; j < columns; j++) {
            arr[i][j] = 0;
        }
    }
}

The result is:

其结果是:

Array(11)
0:(12) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
1:(12) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
2:(12) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
3:(12) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
4:(12) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
5:(12) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
6:(12) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
7:(12) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
8:(12) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
9:(12) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
10:(12)[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

#8


-2  

We usually know the number of columns but maybe not rows (records). Here is an example of my solution making use of much of the above here. (For those here more experienced in JS than me - pretty much everone - any code improvement suggestions welcome)

我们通常知道列的数量,但可能不知道行(记录)。这里有一个例子说明我的解决方案利用了上面的大部分。(对于那些在JS方面比我更有经验的人——几乎所有人——欢迎任何代码改进建议)

     var a_cols = [null,null,null,null,null,null,null,null,null];
     var a_rxc  = [[a_cols]];

     // just checking  var arr =  a_rxc.length ; //Array.isArray(a_rxc);
     // alert ("a_rxc length=" + arr) ; Returned 1 
     /* Quick test of array to check can assign new rows to a_rxc. 
        i can be treated as the rows dimension and  j the columns*/
       for (i=0; i<3; i++) {
          for (j=0; j<9; j++) {
            a_rxc[i][j] = i*j;
            alert ("i=" + i + "j=" + j + "  "  + a_rxc[i][j] );
           }
          if (i+1<3) { a_rxc[i+1] = [[a_cols]]; }
        }

And if passing this array to the sever the ajax that works for me is

如果将这个数组传递给服务器,那么对我有效的ajax就是

 $.post("../ajax/myservercode.php",
       {
        jqArrArg1 : a_onedimarray,
        jqArrArg2 : a_rxc
       },
       function(){  },"text" )
        .done(function(srvresp,status) { $("#id_PageContainer").html(srvresp);} ) 
        .fail(function(jqXHR,status) { alert("jqXHR AJAX error " + jqXHR + ">>" + status );} );

#1


54  

You can just declare a regular array like so:

可以声明一个常规数组,如下所示:

var arry = [];

Then when you have a pair of values to add to the array, all you need to do is:

然后,当您有一对值添加到数组中时,您需要做的就是:

arry.push([value_1, value2]);

And yes, the first time you call arry.push, the pair of values will be placed at index 0.

是的,你第一次给arry打电话。push,这对值将被放置在索引0处。

From the nodejs repl:

从nodejs repl:

> var arry = [];
undefined
> arry.push([1,2]);
1
> arry
[ [ 1, 2 ] ]
> arry.push([2,3]);
2
> arry
[ [ 1, 2 ], [ 2, 3 ] ]

Of course, since javascript is dynamically typed, there will be no type checker enforcing that the array remains 2 dimensional. You will have to make sure to only add pairs of coordinates and not do the following:

当然,由于javascript是动态类型化的,因此没有类型检查器强制要求数组保持二维。您必须确保只添加对的坐标,而不做以下工作:

> arry.push(100);
3
> arry
[ [ 1, 2 ],
  [ 2, 3 ],
  100 ]

#2


15  

If you want to be able access the matrix like so matrix[i][j]

如果你想像这样访问矩阵[i][j]

I find it the most convinient to init it in a loop.

我发现在循环中初始化它是最方便的。

var matrix = [],
    cols = 3;

//init the grid matrix
for ( var i = 0; i < cols; i++ ) {
    matrix[i] = []; 
}

this will give you [ [], [], [] ]

这将给你[],[],[]

so matrix[0][0] matrix[1][0] return undefined and not the error "Uncaught TypeError: Cannot set property '0' of undefined"

因此,矩阵[0][0]矩阵[1][0]返回未定义的,而不是错误“未捕获的类型错误:不能设置未定义的属性‘0’”

#3


4  

An empty array is defined by omitting values, like so:

空数组的定义是省略值,如下所示:

v=[[],[]]
a=[]
b=[1,2]
a.push(b)
b==a[0]

#4


4  

You can nest one array within another using the shorthand syntax:

您可以使用速记语法将一个数组嵌套到另一个数组中:

   var twoDee = [[]];

#5


1  

You can try something like this:-

你可以试试这个:-。

var arr = new Array([]);

Push data:

推动数据:

arr[0][0] = 'abc xyz';

#6


1  

What's wrong with

有什么问题

var arr2 = new Array(10,20);
    arr2[0,0] = 5;
    arr2[0,1] = 2
    console.log("sum is   " + (arr2[0,0] +  arr2[0,1]))

should read out "sum is 7"

应该读出"sum is 7"

#7


1  

You can fill an array with arrays using a function:

你可以用一个函数来填充数组:

var arr = [];
var rows = 11;
var columns = 12;

fill2DimensionsArray(arr, rows, columns);

function fill2DimensionsArray(arr, rows, columns){
    for (var i = 0; i < rows; i++) {
        arr.push([0])
        for (var j = 0; j < columns; j++) {
            arr[i][j] = 0;
        }
    }
}

The result is:

其结果是:

Array(11)
0:(12) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
1:(12) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
2:(12) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
3:(12) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
4:(12) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
5:(12) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
6:(12) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
7:(12) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
8:(12) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
9:(12) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
10:(12)[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

#8


-2  

We usually know the number of columns but maybe not rows (records). Here is an example of my solution making use of much of the above here. (For those here more experienced in JS than me - pretty much everone - any code improvement suggestions welcome)

我们通常知道列的数量,但可能不知道行(记录)。这里有一个例子说明我的解决方案利用了上面的大部分。(对于那些在JS方面比我更有经验的人——几乎所有人——欢迎任何代码改进建议)

     var a_cols = [null,null,null,null,null,null,null,null,null];
     var a_rxc  = [[a_cols]];

     // just checking  var arr =  a_rxc.length ; //Array.isArray(a_rxc);
     // alert ("a_rxc length=" + arr) ; Returned 1 
     /* Quick test of array to check can assign new rows to a_rxc. 
        i can be treated as the rows dimension and  j the columns*/
       for (i=0; i<3; i++) {
          for (j=0; j<9; j++) {
            a_rxc[i][j] = i*j;
            alert ("i=" + i + "j=" + j + "  "  + a_rxc[i][j] );
           }
          if (i+1<3) { a_rxc[i+1] = [[a_cols]]; }
        }

And if passing this array to the sever the ajax that works for me is

如果将这个数组传递给服务器,那么对我有效的ajax就是

 $.post("../ajax/myservercode.php",
       {
        jqArrArg1 : a_onedimarray,
        jqArrArg2 : a_rxc
       },
       function(){  },"text" )
        .done(function(srvresp,status) { $("#id_PageContainer").html(srvresp);} ) 
        .fail(function(jqXHR,status) { alert("jqXHR AJAX error " + jqXHR + ">>" + status );} );