I wrote a function calcNewtonPath with 4 parameters as below. However when i call it, the function changes the value of parameter matA unexpectedly and i can't understand why.
function calcNewtonPath(matA,matB,m,n){
let temp = matA.slice() //i tried this to prevent the unexpected change but it didn't work
for(let i=0;i<m;i++){
temp[i].push(-matB[i])
}
return matrix.solve(temp,m,n)
}
The function solve also changes the value of temp too! But it's a bit complicated so i think i will not put the code here.
Can anyone help me about this?
UPDATED:
.slice() will just do a shallow copy.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice
That means for example:
const a = [[1,2,3]]
const b = slice.a();
b[0][1] = 4;
a array will also be changed.
a will be [[1,4,3]] as well as b;
One easy solution would be to make a deep copy of an array:
const deepCopy = JSON.parse(JSON.stringify(array));