In python, you can do this:
[([None] * 9) for x in range(9)]
and you\'ll get this:
[[None, None, None, None, None, None, No
Coffeescript to the rescue!
[1..9].map -> [1..9].map -> null
Array.from(new Array(row), () => new Array(col).fill(0));
Use this function or some like that. :)
function createMatrix(line, col, defaultValue = 0){
return new Array(line).fill(defaultValue).map((x)=>{ return new Array(col).fill(defaultValue); return x; });
}
var myMatrix = createMatrix(9,9);
The question is slightly ambiguous, since None
can translate into either undefined
or null
. null
is a better choice:
var a = [], b;
var i, j;
for (i = 0; i < 9; i++) {
for (j = 0, b = []; j < 9; j++) {
b.push(null);
}
a.push(b);
}
If undefined
, you can be sloppy and just don't bother, everything is undefined
anyway. :)
// initializing depending on i,j:
var M=Array.from({length:9}, (_,i) => Array.from({length:9}, (_,j) => i+'x'+j))
// Print it:
console.table(M)
// M.forEach(r => console.log(r))
document.body.innerHTML = `<pre>${M.map(r => r.join('\t')).join('\n')}</pre>`
// JSON.stringify(M, null, 2) // bad for matrices
Beware that doing this below, is wrong:
// var M=Array(9).fill([]) // since arrays are sparse
// or Array(9).fill(Array(9).fill(0))// initialization
// M[4][4] = 1
// M[3][4] is now 1 too!
Because it creates the same reference of Array 9 times, so modifying an item modifies also items at the same index of other rows (since it's the same reference), so you need an additional call to .slice or .map on the rows to copy them (cf torazaburo's answer which fell in this trap)
note: It may look like this in the future, with slice-notation-literal proposal (stage 1)
const M = [...1:10].map(i => [...1:10].map(j => i+'x'+j))
There is something about Array.fill
I need to mention.
If you just use below method to create a 3x3 matrix.
Array(3).fill(Array(3).fill(0));
You will find that the values in the matrix is a reference.
If you want to pass by value rather than reference, you can leverage Array.map
to create it.
Array(3).fill(null).map(() => Array(3).fill(0));