I've got function that creates x*y
array with some default value. I want this value to be some array 2-long
But then it's not a x*y
2-dimensional array any more, but a x*y*2
3-dimensional array! And for that, you need a different function.
it seems that by passing new Array(2)
as parameter it always pass the same object, so later changing any of cell in array affects all of them.
Yes. new Array(2)
creates one object, and your code constructs a 2-dimensional array with every field pointing to it.
How to make them independent?
You'll need to use a different function, like
function newB(x, y, z) {
var result = new Array(x);
for (var i=0; i<x; i++) {
result[i] = new Array(y);
for (var j=0; j<y; j++) {
result[i][j] = new Array(z);
}
}
return result;
}
var fields = newA(5, 5, 2);
Or to make it more general, you can use some factory function as a parameter, which constructs the independent values:
function newB(x, y, valuemaker) {
if (typeof valuemaker != "function") {
var value = valuemaker || 0;
valuemaker = function(){ return value; };
}
var result = new Array(x);
for (var i=0; i<x; i++) {
result[i] = new Array(y);
for (var j=0; j<y; j++) {
result[i][j] = valuemaker();
}
}
return result;
}
var fields = newA(5, 5, function() {
return new Array(2);
});