I'm having a trouble when I want to create a multidimensional array.
I don't know why but I get a strange behavior when I want to create a multidimensional array with an object as default value.
I have used different ways like:
- https://stackoverflow.com/a/41435124/1741027
- https://stackoverflow.com/a/28625612/1741027
- https://stackoverflow.com/a/18116922/1741027
The trouble appears when I want to change anyone of fields of the object.
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;
}
var myArray = matrix(5, 5, {
status: 'OK'
});
myArray[2][1].status = 'NOT OK';
console.log('Strange behavior', myArray);
The change expands on the other positions.
Can anybody help me?