I'm trying to create a 3d matrix in javascript, and then I want to update its values by using its coordinates:
var xAxis = [];
var yAxis = [];
var ZAxis = [];
var dimensions = 4;
//initalize matrix
for (var i=0;i<dimensions;i++){
xAxis.push(0);
}
for (var j=0;j<dimensions;j++){
yAxis.push(xAxis);
}
for (var k=0;k<dimensions;k++){
matrix.push(yAxis);
}
//check value of one point in the matrix
matrix[1][2][3]; //returns 0 as expected
//update value of matrix using same coordinates
matrix[1][2][3] = 2;
When I run the last step, it will not only update my expected 1[2][3] coordinates, but it also updates every third value of every array to 2 as you will see in the image:
How can I manage to update only the value that I want?? I mean, the number 2 should only be in one coordinate point, in this case 1[2][3].
Note: I think it's got something to do that it might be assigning the original arrays into the matrix instead of new copies of themselves, so when I update one coordinate, I'm actually updating the original array, and the other arrays are just pointing at the original, so that's why it's been reflected there as well?
答案 0 :(得分:2)
You push arrays by reference.
Consider creating your matrix this way:
var matrix = [0, 1, 2, 3].map(function() {
return new Array(4).fill().map(function(){
return new Array(4).fill(0);
});
});
答案 1 :(得分:0)
You are not creating copies if your array but pass references.
You could use a function to create n dim matrices
var createMatrix = function(dimensions, level) {
if (level === undefined) {
level = dimensions - 1
}
var arr = [];
for (var j = 0; j < dimensions; j++){
arr[j] = level === 0 ? 0 : createMatrix(dimensions, level-1)
}
}
return arr
}
var matrix = createMatrix(3)