Use Array Comprehensions
In JavaScript 1.7 and higher you can use array comprehensions to create two dimensional arrays. You can also filter and/or manipulate the entries while filling the array and don't have to use loops.
var rows = [1, 2, 3];
var cols = ["a", "b", "c", "d"];
var grid = [ for (r of rows) [ for (c of cols) r+c ] ];
/*
grid = [
["1a","1b","1c","1d"],
["2a","2b","2c","2d"],
["3a","3b","3c","3d"]
]
*/
You can create any n x m
array you want and fill it with a default value by calling
var default = 0; // your 2d array will be filled with this value
var n_dim = 2;
var m_dim = 7;
var arr = [ for (n of Array(n_dim)) [ for (m of Array(m_dim) default ]]
/*
arr = [
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
]
*/
More examples and documentation can be found here.
Please note that this is not a standard feature yet.
var arr2D = new Array(5).fill(new Array(3));
, each element of Array(5) will point to the same Array(3). So it's best to use a for loop to dynamically populate sub arrays. – Josh Striblinga = Array(5).fill(0).map(x => Array(10).fill(0))
– Longfei Wufill
doesn't callnew Array(3)
for each index of the array being filled, since it's not a lambda expression or anything, such as Longfei Wu's comment above, which initially fills the array with 0's, then uses the map function with a lambda to fill each element with a new array. The fill function simply fills the array with exactly what you tell it to. Does that make sense? For more info on themap
function, see: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… – Josh StriblingIf the new question is a better question or has better answers, then vote to close the old one as a duplicate of the new one.
– Adam