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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18163234/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 10:56:24  来源:igfitidea点击:

Declare an empty two-dimensional array in Javascript?

javascriptarraysdynamic2dpush

提问by Zannix

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:

预定义二维数组示例:

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 新手,如果有人可以编写一个我可以检查的简短工作代码片段,我将不胜感激。谢谢

回答by DJG

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 复制:

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

回答by AbhinavD

If you want to initialize along with the creation, you can use filland map.

如果你想和创建一起初始化,你可以使用fillmap

const matrix = new Array(5).fill(0).map(() => new Array(4).fill(0));

5 is the number of rows and 4 is the number of columns.

5 是行数,4 是列数。

回答by Kamil Kie?czewski

ES6

ES6

Matrix mwith size 3 rows and 5 columns (remove .fill(0)to not init by zero)

m大小为 3 行和 5 列的矩阵(删除.fill(0)以不以零初始化)

[...Array(3)].map(x=>Array(5).fill(0))       

let Array2D = (r,c) => [...Array(r)].map(x=>Array(c).fill(0));

let m = Array2D(3,5);

m[1][0] = 2;  // second row, first column
m[2][4] = 8;  // last row, last column

// print formated array
console.log(JSON.stringify(m)
  .replace(/(\[\[)(.*)(\]\])/g,'[\n  []\n]').replace(/],/g,'],\n  ')
);

回答by Lorenzo Gangi

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

如果您希望能够像这样访问矩阵 matrix[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'”

回答by Kevin Bowersox

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

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

   var twoDee = [[]];

回答by Rahul Tripathi

You can try something like this:-

你可以尝试这样的事情:-

var arr = new Array([]);

Push data:

推送数据:

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

回答by UIlrvnd

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

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

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

回答by Bj?rn Hallstr?m

Create an object and push that object into an array

创建一个对象并将该对象推入一个数组

 var jSONdataHolder = function(country, lat, lon) {

    this.country = country;
    this.lat = lat;
    this.lon = lon;
}

var jSONholderArr = [];

jSONholderArr.push(new jSONdataHolder("Sweden", "60", "17"));
jSONholderArr.push(new jSONdataHolder("Portugal", "38", "9"));
jSONholderArr.push(new jSONdataHolder("Brazil", "23", "-46"));

var nObj = jSONholderArr.length;
for (var i = 0; i < nObj; i++) {
   console.log(jSONholderArr[i].country + "; " + jSONholderArr[i].lat + "; " + 
   jSONholderArr[i].lon);

}

回答by MadHaka

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”

回答by entoniperez

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]