如何在JavaScript中创建二维数组?

JavaScript

Stafan古一

2020-03-09

我一直在网上阅读,有些地方说这是不可能的,有些地方说是不可能,然后举一个例子,其他人则反驳该例子,等等。

  1. 如何在JavaScript中声明二维数组?(假设有可能)

  2. 我将如何访问其成员?myArray[0][1]myArray[0,1]?)

第377篇《如何在JavaScript中创建二维数组?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

16个回答
NearGreen 2020.03.09

I found that this code works for me:

var map = [
    []
];

mapWidth = 50;
mapHeight = 50;
fillEmptyMap(map, mapWidth, mapHeight);

...

function fillEmptyMap(array, width, height) {
    for (var x = 0; x < width; x++) {
        array[x] = [];
        for (var y = 0; y < height; y++) {

            array[x][y] = [0];
        }
    }
}
老丝Jim猴子 2020.03.09

You could allocate an array of rows, where each row is an array of the same length. Or you could allocate a one-dimensional array with rows*columns elements and define methods to map row/column coordinates to element indices.

Whichever implementation you pick, if you wrap it in an object you can define the accessor methods in a prototype to make the API easy to use.

NearItachi 2020.03.09

There is another solution, that does not force you to pre-define the size of the 2d array, and that is very concise.

var table = {}
table[[1,2]] = 3 // Notice the double [[ and ]]
console.log(table[[1,2]]) // -> 3

This works because, [1,2] is transformed into a string, that is used as a string key for the table object.

斯丁Sam斯丁 2020.03.09

ES6+, ES2015+ can do this in even simpler way


Creating 3 x 2 Array filled with true

[...Array(3)].map(item => Array(2).fill(true))
阳光猿 2020.03.09

Below one, creates a 5x5 matrix and fill them with null

var md = [];
for(var i=0; i<5; i++) {
    md.push(new Array(5).fill(null));
}

console.log(md);

Green达蒙 2020.03.09

I found below is the simplest way:

var array1 = [[]];   
array1[0][100] = 5; 

alert(array1[0][100]);
alert(array1.length);
alert(array1[0].length);
Gil伽罗 2020.03.09

For one liner lovers Array.from()

// creates 8x8 array filed with "0"    
const arr2d = Array.from({ length: 8 }, () => Array.from({ length: 8 }, () => "0"))

Another one (from comment by dmitry_romanov) use Array().fill()

// creates 8x8 array filed with "0"    
const arr2d = Array(8).fill(0).map(() => Array(8).fill("0"))

Using ES6+ spread operator ("inspired" by InspiredJW answer :) )

// same as above just a little shorter
const arr2d = [...Array(8)].map(() => Array(8).fill("0"))
古一NearEva 2020.03.09

To create a non-sparse "2D" array (x,y) with all indices addressable and values set to null:

let 2Darray = new Array(x).fill(null).map(item =>(new Array(y).fill(null))) 

bonus "3D" Array (x,y,z)

let 3Darray = new Array(x).fill(null).map(item=>(new Array(y).fill(null)).map(item=>Array(z).fill(null)))

Variations and corrections on this have been mentioned in comments and at various points in response to this question but not as an actual answer so I am adding it here.

It should be noted that (similar to most other answers) this has O(x*y) time complexity so it probably not suitable for very large arrays.

小哥Jim 2020.03.09

This is what i achieved :

var appVar = [[]];
appVar[0][4] = "bineesh";
appVar[0][5] = "kumar";
console.log(appVar[0][4] + appVar[0][5]);
console.log(appVar);

This spelled me bineeshkumar

Green小胖 2020.03.09

Two-liner:

var a = []; 
while(a.push([]) < 10);

It will generate an array a of the length 10, filled with arrays. (Push adds an element to an array and returns the new length)

达蒙小哥 2020.03.09

Two dimensional arrays are created the same way single dimensional arrays are. And you access them like array[0][1].

var arr = [1, 2, [3, 4], 5];

alert (arr[2][1]); //alerts "4"
Harry乐Gil 2020.03.09

Few people show the use of push:
To bring something new, I will show you how to initialize the matrix with some value, example: 0 or an empty string "".
Reminding that if you have a 10 elements array, in javascript the last index will be 9!

function matrix( rows, cols, defaultValue){

  var arr = [];

  // Creates all lines:
  for(var i=0; i < rows; i++){

      // Creates an empty line
      arr.push([]);

      // Adds cols to the empty line:
      arr[i].push( new Array(cols));

      for(var j=0; j < cols; j++){
        // Initializes:
        arr[i][j] = defaultValue;
      }
  }

return arr;
}

usage examples:

x = matrix( 2 , 3,''); // 2 lines, 3 cols filled with empty string
y = matrix( 10, 5, 0);// 10 lines, 5 cols filled with 0
米亚神无 2020.03.09

The easiest way:

var myArray = [[]];
阿飞西里 2020.03.09

您只需将数组中的每个项目都设为一个数组。

var x = new Array(10);

for (var i = 0; i < x.length; i++) {
  x[i] = new Array(3);
}

console.log(x);

古一L 2020.03.09

Javascript only has 1-dimensional arrays, but you can build arrays of arrays, as others pointed out.

The following function can be used to construct a 2-d array of fixed dimensions:

function Create2DArray(rows) {
  var arr = [];

  for (var i=0;i<rows;i++) {
     arr[i] = [];
  }

  return arr;
}

The number of columns is not really important, because it is not required to specify the size of an array before using it.

Then you can just call:

var arr = Create2DArray(100);

arr[50][2] = 5;
arr[70][5] = 7454;
// ...
老丝猿路易 2020.03.09

var items = [
  [1, 2],
  [3, 4],
  [5, 6]
];
console.log(items[0][0]); // 1
console.log(items[0][1]); // 2
console.log(items[1][0]); // 3
console.log(items[1][1]); // 4
console.log(items);

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android