I'm trying to write a web-based curve fitting program for my students. In order to do this I need to understand how 2D arrays (arrays of arrays) work in javascript, and it is pretty clear that I don't. In the code below, I expect the two loops that write to the console to give the same result, but they don't. The first one gives what I expect. The second one is mysterious to me. It gives the same result as a simple console.log(q);
Just to be clear, the solution provided in Copying array by value in JavaScript does not work. If I create the array c, then create q by
var q = c.slice();
when I compute the inverse of the matrix c, I find that q has also been inverted. I need to have both the inverted and uninverted versions of the matrix handy...
var q = [];
var c = [];
var row = [];
// create the array q
for (i=0; i<4; i++) {
row.push(0);
}
for (i=0; i<4; i++) {
q.push(row);
}
// create the array c
c.push([1, 2, 5, 1]);
c.push([3, -4, 3, -2]);
c.push([4, 3, 2, -1]);
c.push([1, -2, -4, -1]);
for (var i=0; i<4; i++) {
for (var j=0; j<4; j++) {
q[i][j] = c[i][j];
console.log(q[i][j]);
}
}
console.log('-------------------------')
for (var i=0; i<4; i++) {
for (var j=0; j<4; j++) {
console.log(q[i][j]);
}
}
.as-console-wrapper { max-height: 100% !important; top: 0; }