I have a for loop like below
let oArr = [1,1,1,1,1,1,1,1,1]
let n = 9
let k = 5
let mArr = []
for (let j = 0; j < k; j++) {
for (let i = 0; i < n; i++) {
if (i === 0) {
mArr[i] = oArr[0] + oArr[1]
} else if (i === (n - 1)) {
mArr[i] = oArr[i] + oArr[i - 1]
} else {
mArr[i] = oArr[i] + oArr[i + 1] + oArr[i - 1]
}
}
console.log(`j == ${j},mArr == ${mArr}`)
oArr = mArr
}
so it should be
mArr[1] = oArr[1] + oArr[2] + oArr[0]
since oArr = mArr is outside the for(i) loop
but the output I get is like below
mArr[1] = oArr[1]*2 + oArr[2] + oArr[0]
Please tell me what went wrong?
is there a misplacement of
oArr = mArr
2
Answers
you should change your code as below:
creating a new mArr array within each iteration of the outer loop, you ensure that the calculations are performed on the original oArr values without any interference from previous iterations.
Then, after the inner loop is completed, you update oArr with the newly calculated values stored in mArr, I hope it helps.
When you do
You are not copying the arrays, but in fact both are pointing to the very same array. So when you then do
in the next iteration of the outer loop, you are not only modifying the first element of
mArr
but also ofoArr
. Same for all other assignments. Useto create a copy of your array instead of both pointing to the same array.