简体   繁体   English

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

[英]Declare an empty two-dimensional array in Javascript?

I want to create a two dimensional array in Javascript where I'm going to store coordinates (x,y).我想在 Javascript 中创建一个二维数组,我将在其中存储坐标 (x,y)。 I don't know yet how many pairs of coordinates I will have because they will be dynamically generated by user input.我还不知道我将拥有多少对坐标,因为它们将由用户输入动态生成。

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.这可能很容易做到,我只是 JS 的新手,如果有人可以编写一个我可以检查的简短工作代码片段,我将不胜感激。 Thanks谢谢

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.当然,由于 javascript 是动态类型的,因此不会强制执行数组保持二维的类型检查器。 You will have to make sure to only add pairs of coordinates and not do the following:您必须确保只添加坐标对,而不是执行以下操作:

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

If you want to initialize along with the creation, you can use fill and 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 是列数。

ES6 ES6

Matrix m with 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 [$2]\\n]').replace(/],/g,'],\\n ') );

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'”

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

   var twoDee = [[]];

You can try something like this:-你可以尝试这样的事情:-

var arr = new Array([]);

Push data:推送数据:

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

An empty array is defined by omitting values, like so:空数组是通过省略值来定义的,如下所示:

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

I know this is an old thread but I'd like to suggest using an array of objects rather than an array of arrays .我知道这是一个旧线程,但我想建议使用array of objects而不是array of arrays I think it make the code simpler to understand and update.我认为它使代码更易于理解和更新。

 // Use meaningful variable names like 'points', // anything better than a bad pirate joke, 'arr'! var points = []; // Create an object literal, then add it to the array var point = {x: 0, y: 0}; points.push(point); // Create and add the object to the array in 1 line points.push({x:5, y:5}); // Create the object from local variables var x = 10; var y = 8; points.push({x, y}); // Ask the user for a point too var response = prompt("Please enter a coordinate point. Example: 3,8"); var coords = response.split(",").map(Number); points.push({x: coords[0], y: coords[1]}); // Show the results var canvas = document.getElementById('graph'); var painter = canvas.getContext("2d"); var width = canvas.width, height = canvas.height; var scale = 10, radius = 3.5, deg0 = 0, deg360 = 2 * Math.PI; painter.beginPath(); for (var point of points) { var x = point.x * scale + scale; var y = height - point.y * scale - scale; painter.moveTo(x + radius, y); painter.arc(x, y, radius, deg0, deg360); painter.fillText(`${point.x}, ${point.y}`, x + radius + 1, y + radius + 1); } painter.stroke();
 <canvas id="graph" width="150" height="150" style="border: 1px solid red;"></canvas>

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]

const grid = Array.from(Array(3), e => Array(4));

Array.from(arrayLike, mapfn)

mapfn is called, being passed the value undefined , returning new Array(4) . mapfn被调用,被传递值undefined ,返回new Array(4)

An iterator is created and the next value is repeatedly called.创建迭代器并重复调用next值。 The value returned from next , next().value is undefined .nextnext().value value 返回的next().valueundefined This value, undefined , is then passed to the newly-created array's iterator.这个值undefined然后被传递给新创建的数组的迭代器。 Each iteration's value is undefined , which you can see if you log it.每次迭代的value都是undefined ,如果你记录它,你可以看到它。

var grid2 = Array.from(Array(3), e => {
  console.log(e); // undefined
  return Array(4); // a new Array.
});

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

}

 var arr = []; var rows = 3; var columns = 2; for (var i = 0; i < rows; i++) { arr.push([]); // creates arrays in arr } console.log('elements of arr are arrays:'); console.log(arr); for (var i = 0; i < rows; i++) { for (var j = 0; j < columns; j++) { arr[i][j] = null; // empty 2D array: it doesn't make much sense to do this } } console.log(); console.log('empty 2D array:'); console.log(arr); for (var i = 0; i < rows; i++) { for (var j = 0; j < columns; j++) { arr[i][j] = columns * i + j + 1; } } console.log(); console.log('2D array filled with values:'); console.log(arr);

ES6 ES6

 const rows = 2; const columns = 3; const matrix = [...Array(rows)].map(() => [...Array(columns)].fill(0)); console.log(matrix);

The most simple way to create an empty matrix is just define it as an empty array:创建空矩阵的最简单方法就是将其定义为空数组:

// Empty data structure
const matrix = []

However, we want to represent something similar to a grid with n and m parameters know ahead then we can use this instead.但是,我们想用预先知道的nm参数来表示类似于网格的东西,然后我们可以使用它来代替。

// n x m data structure
const createGrid = (n, m) => [...Array(n)].map(() => [...Array(m)].fill(0))
const grid = createGrid(3, 5)

Here is a simple snippet showing how to use them.这是一个简单的片段,展示了如何使用它们。

 const createGrid = (n, m) => [...Array(n)].map(() => [...Array(m)].fill(0)) const toString = m => JSON.stringify(m).replace(/(\[\[)(.*)(]])/g, '[\n [$2]\n]').replace(/],/g, '],\n ') // Empty data structure const matrix = [] console.log(toString(matrix)) matrix.push([1,2,3]) matrix.push([4,5,6]) matrix.push([7,8,9]) console.log(toString(matrix)) // nxm data structure const grid = createGrid(3, 5) console.log(toString(grid))

If we don't use ES2015 and don't have fill(), just use .apply()如果我们不使用 ES2015 并且没有 fill(),只需使用.apply()

See https://stackoverflow.com/a/47041157/1851492https://stackoverflow.com/a/47041157/1851492

 let Array2D = (r, c, fill) => Array.apply(null, new Array(r)).map(function() {return Array.apply(null, new Array(c)).map(function() {return fill})}) console.log(JSON.stringify(Array2D(3,4,0))); console.log(JSON.stringify(Array2D(4,5,1)));

No need to do so much of trouble!没必要做那么多麻烦! Its simple这很简单

This will create 2 * 3 matrix of string.这将创建 2 * 3 的字符串矩阵。

var array=[];
var x = 2, y = 3;
var s = 'abcdefg';

for(var i = 0; i<x; i++){
    array[i]=new Array();
      for(var j = 0; j<y; j++){
         array[i].push(s.charAt(counter++));
        }
    }

One line solution:一行解决方案:

var x = 3, y = 4;

var ar = new Array(x).fill(new Array(y).fill(0));

It creates matrix array with values = 0它创建值 = 0 的矩阵数组

You can nest a new array as you fill the first one:您可以在填充第一个数组时嵌套一个新数组:

let ROWS = 2,
    COLS = 6;
let arr = new Array(ROWS).fill(new Array(COLS).fill(-1));
Output:
arr = 
[
  [-1, -1, -1, -1, -1, -1],
  [-1, -1, -1, -1, -1, -1]
]

If you're confused, lets break this down with declaring/filling 1 array: Make a new array size d, filled with any initial value如果你感到困惑,让我们通过声明/填充 1 个数组来分解它:创建一个新的数组大小为 d,填充任何初始值

let arr1d = new Array(d).fill(<whatever_fill_val>);

Now, instead of filling your first array with a int/string/etc, you can fill it with ANOTHER array, as you fill the nested one!现在,您可以用另一个数组填充它,而不是用 int/string/etc 填充第一个数组,就像填充嵌套数组一样!

let arr = new Array(d).fill(new Array(n).fill(-1));

One Liner一个班轮

let m = 3 // rows
let n = 3 // columns
let array2D = Array(m).fill().map(entry => Array(n))

This implementation creates a unique subarray for each entry.此实现为每个条目创建一个唯一的子数组。 So setting array2D[0][1] = 'm' does not set each entry's [1] index to 'm'因此,设置array2D[0][1] = 'm'不会将每个条目的 [1] 索引设置为 'm'

This one should work:这个应该工作:

const arr = new Array(5).fill().map(_ => new Array(5).fill(0)) // ✅

You may ask why did I use map instead of:您可能会问为什么我使用 map 而不是:

const badArr = new Array(5).fill(new Array(5).fill(0)) // ❌

The problem with the example above is that it adds references to the array that was passed into the fill method:上面示例的问题在于它添加了对传递给 fill 方法的数组的引用:

在此处输入图像描述

While this one works fine:虽然这个工作正常:

在此处输入图像描述

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”

const dp=new Array(3).fill(new Array(3).fill(-1))

It will create below array:它将创建以下数组:

[ [ -1, -1, -1 ], [ -1, -1, -1 ], [ -1, -1, -1 ] ]

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

// 对于 3 x 5 数组

new Array(3).fill(new Array(5).fill(0))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM