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
Well, you can create an empty 1-D array using the explicit Array constructor:
a = new Array(9)
To create an array of arrays, I think that you'll have to write a nested loop as Marc described.
I'll give it my shot as well
var c = Array;
for( var i = 0, a = c(9); i < 9; a[i] = c(9), i++ );
console.log( a.join(",") );
//",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,"
Readable and maintainable !
better. that exactly will work.
let mx = Matrix(9, 9);
function Matrix(w, h){
let mx = Array(w);
for(let i of mx.keys())
mx[i] = Array(h);
return mx;
}
what was shown
Array(9).fill(Array(9)); // Not correctly working
It does not work, because all cells are fill with one array
var matrix = [];
for(var i=0; i<9; i++) {
matrix[i] = new Array(9);
}
... or:
var matrix = [];
for(var i=0; i<9; i++) {
matrix[i] = [];
for(var j=0; j<9; j++) {
matrix[i][j] = undefined;
}
}
You can add functionality to an Array by extending its prototype
object.
Array.prototype.nullify = function( n ) {
n = n >>> 0;
for( var i = 0; i < n; ++i ) {
this[ i ] = null;
}
return this;
};
Then:
var arr = [].nullify(9);
or:
var arr = [].nullify(9).map(function() { return [].nullify(9); });
Here's one, no looping:
(Math.pow(10, 20)+'').replace((/0/g),'1').split('').map(parseFloat);
Fill the '20' for length, use the (optional) regexp for handy transforms and map to ensure datatype. I added a function to the Array prototype to easily pull the parameters of 'map' into your functions.. bit risky, some people strongly oppose touching native prototypes, but it does come in handy..
Array.prototype.$args = function(idx) {
idx || (idx = 0);
return function() {
return arguments.length > idx ? arguments[idx] : null;
};
};
// Keys
(Math.pow(10, 20)+'').replace((/0/g),'1').split('').map(this.$args(1));
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
// Matrix
(Math.pow(10, 9)+'').replace((/0/g),'1').split('').map(this.$args(1)).map(this.$args(2))