javascript .push()添加到两个数组

我想找到最长的collat​​z序列序列低于100,并且此代码输出2,这不是答案。当我观察变量时,每当.push()函数将某些内容添加到睾丸中时,它也会添加到最大值中。为什么要在两者的末尾添加一个值?

    var n;
var m;
var testary = [];
var maxary = [];
var max;
for(i=2;i<100;i++){
    n = i;
    m = i;
    while(n>1){
        if(n%2 == 0){
            testary.push(n);
            n = n/2;
    }   else if(n%2 != 0){
            testary.push(n);
            n = (3*n)+1;
    }
    if(testary.length>maxary.length){
        maxary = testary;
        max = m;
    }
}}
评论
  • 情侣~装
    情侣~装 回复

    When you assign maxary = testary it assigns the reference of testary to maxary and whenever you try to add item using push to any one of them it will affect both the array as the value is changed at the reference in javascript

    You can clone the array before assigning using spread syntax

    var n;
    var m;
    var testary = [];
    var maxary = [];
    var max;
    for(i=2;i<100;i++){
        n = i;
        m = i;
        while(n>1){
            if(n%2 == 0){
                testary.push(n);
                n = n/2;
        }   else if(n%2 != 0){
                testary.push(n);
                n = (3*n)+1;
        }
        if(testary.length>maxary.length){
            maxary = [...testary]; // clone the array
            max = m;
        }
    }}