2017-09-14 144 views
0

我希望有人能解釋我的for循環出了什麼問題。如果我輸入for循環if(arguments [2]){stable = rere(stable,arguments [2]);}它按預期工作。我可以有超過6個參數,並且想知道爲什麼這個循環無法正常工作。有限循環崩潰瀏覽器

function sym() { 
    function rere(a,b){ 
    var check = []; 
    for(i=a.length-1; i>=0; i--){ 
     for(x=b.length-1; x>=0; x--){ 
     if(a[i] == b[x]){ 
      check.push(a.splice(i,1));   
     } 
     } 
    } 

    for(i=b.length-1; i>=0; i--){ 
     for(x=check.length-1; x>=0; x--){ 
     if(b[i] == check[x][0]){ 
      b.splice(i,1); 
     } 
     } 
    } 
    var stable = a.concat(b); 
    return stable; 
    } 
    var stable = rere(arguments[0], arguments[1]); 

//problem is HERE. The for loop repeating rere function crashes repl.it 

    for(i=2; i<arguments.length; i++){ 
    stable = rere(stable, arguments[i]); 
    } 
//End problem. 

    stable = stable.filter(function(a,b,c){ 
    return b == c.indexOf(a); 
    }); 
    return stable; 
} 

sym([3, 3, 3, 2, 5], [2, 1, 5, 7], [3, 4, 6, 6], [1, 2, 3], [5, 3, 9, 8], [1]); 
+0

什麼是錯誤? – TechJS

+0

所以你想過濾出重複? –

回答

1

你在rere()沒有宣佈它重用i變量,因此它得到的問題,每次循環迭代復位。

要解決該問題,請在rere()內使用letvar正確聲明i

+0

如果他聲明,它也會重置。沒有? – TechJS

+0

不僅如此:在代碼頂部預先設置一個「use strict」行來避免這種常見錯誤是非常明智的。 – bitifet

+0

@techjs不,它關於範圍。 –