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

标签 javascript arrays push

我想找到 100 以下的最长的 collat​​z 序列,这段代码输出 2,这不是答案。当我观察变量时,每当 .push() 函数向 testary 添加一些内容时,它也会添加到 maxary 中。为什么它要在两者的末尾添加一个值?

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;
    }
}}

最佳答案

当您分配maxary = testary时,它会将testary的引用分配给maxary,每当您尝试使用push向其中任何一个添加项目时,它都会影响两个数组,因为值在以下位置更改javascript 中的引用

您可以在分配之前使用 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;
    }
}}

关于javascript .push() 添加到两个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61853011/

相关文章:

git - 推送到 git 存储库时管道损坏

javascript - 在 CRM 2011 中隐藏日期时间字段中的非工作时间

javascript - 看不到场景中的简单几何图形

javascript - 寻找有关如何在鼠标突出显示链接时显示信息警报的选项

c - 如何在 C 的套接字上发送/接收字符串数组

php - 将 PHP 对象转换为关联数组

javascript - jQuery:如何在不显示滚动条的情况下滚动正文?

c++ - 理解 char array[] 和 string

iphone - Apple 推送通知,如何正确导出我的证书?

git - 我如何撤消其他开发人员 git push 到 master 分支