I am trying to write a fairly simple Javascript function, and experiencing behavior I don't understand when I iterate the function.
I have distilled the problem down to the following situation. I want to write a function that will take as input an array consisting of arrays of arrays, e.g. A = [[[1]]]. I don't know the standard terminology for this, so I am going to refer to the main array as "level 0", which has elements that are arrays of "level 1". I'll say the level 1 arrays consist of arrays of "level 2". The level 2 arrays consist of integers.
The function does the following, on input A (a level 0 array):
- create an empty array
L; - for each level 1 array
MinA- add one to each integer entry in each level 2 array in
M; - add two copies of
MtoL
- add one to each integer entry in each level 2 array in
- return
L.
Here is my code:
function myFunc(A){
var L = [];
for(var a=0; a<A.length; a++){
var M = A[a].slice(0);
for(var i=0; i<M.length; i++){
for(var j=0; j<M[i].length; j++){
M[i][j]++;
}
}
for(var s=0; s<2; s++){
var N = M.slice(0);
L.push(N);
}
}
return(L);
}
Now I test it out:
var A = [[[1]]];
A = myFunc(A)
After this, I get A = [[[2]],[[2]]], which is what I expect. However, suppose I iterate it:
var A = [[[1]]];
A = myFunc(A);
A = myFunc(A);
Then I expect to obtain A = [[[3]],[[3]],[[3]],[[3]]], but instead I have A = [[[4]],[[4]],[[4]],[[4]]].
On the other hand if I run myFunc([[[2]],[[2]]]), I do get the expected [[[3]],[[3]],[[3]],[[3]]].
I don't understand where this discrepancy is coming from.
x = [[[1]]]and then callmyFunc(x)multiple times.