简体   繁体   English

javascrip.push() 添加到两个 arrays

[英]javascrip .push() adding to two arrays

I want to find the longest series of collatz sequence under 100 and this code outputs 2, which is not the answer.我想在 100 下找到最长的 collatz 序列序列,此代码输出 2,这不是答案。 when i watch the variables, whenever the.push()function adds something to the testary it also adds to the maxary.当我观察变量时,每当 .push() 函数向 testary 添加一些东西时,它也会添加到 maxary。 Why is it adding a value to the end of both?为什么要在两者的末尾添加一个值?

    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当您分配maxary = testary时,它将 testary 的引用分配给 maxary 并且每当您尝试使用 push 向其中任何一个添加项目时,它都会影响两个数组,因为在 javascript 中的引用处更改了值

You can clone the array before assigning using spread syntax您可以在使用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;
    }
}}

Interesting little puzzle.有趣的小谜题。 Never heard of Collatz before.以前从未听说过科拉茨。 Here is my take on it.这是我的看法。 It will return the top 10 sequence lengths and will show the "winning" sequence.它将返回前 10 个序列长度并显示“获胜”序列。

 var arr,i,n,testary=[]; for(i=2;i<100;i++){ arr=[];n=i; do arr.push(n); while ( (n = n%2? (3*n)+1: n/2) >1 ); testary.push(arr); } testary.sort((a,b)=>b.length-a.length).slice(0,10).forEach(e=>console.log(e[0],e.length)) // show longest found sequence: console.log(testary[0].join(', '))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM