0

I have a problem in this piece of code. The results of console.log() statements are different but I have not changed the value of temp array. How can I solve this problem? Here is my code:

var i , j , temp, main,sum,numb=4;
temp=[1];
main=[];
sum=[];

for(i=1; i<=numb ; i++){
    for(j=0 ; j<=i ; j++){
        if(j==0||j==i){
            main[j]=1;
        }
        else{     
            console.log(temp[j]+"*"+temp[j-1]);
            main[j]=temp[j]+temp[j-1];  
            console.log(temp[j]+"**"+temp[j-1]);
        }
    }
    sum.push(temp);
    temp=main;

}
VLAZ
  • 26,331
  • 9
  • 49
  • 67
hassan yousefi
  • 239
  • 3
  • 14
  • what is it suposed to do? what do you expect? – Nina Scholz Apr 11 '20 at 13:45
  • `temp=main` will not make a *copy* of the array but actually makes `temp` point at the *same* array as `main`. So, between your two `console.log` statements you *do* change `main` which is now *exactly* the same thing as `temp`. If you need to clone the `main` array, you can do `temp = main.slice()` – VLAZ Apr 11 '20 at 13:47
  • @Nina Scholz I have expected the result of 2 console.log be the same – hassan yousefi Apr 11 '20 at 13:49

0 Answers0