2016-08-27 34 views
0

這是一個免費代碼陣營的任務,我的問題是我的for循環沒有迭代,它是一個從filter方法返回的函數,我需要通過除初始數組[0]之外的額外參數循環來比較它是否匹配並刪除。我的循環不是不執行?

此代碼的結果是1,3,1,3,我想要1,1。

function destroyer(arr) { 
    var p = arguments.length; // arr length 
    var r = arguments; // 
    function argScope(item) { 
     debugger; 
     for(var a =1; a<=p; a++) { // start iterate at 1, 0 is the initial array I want to remove elements 
      if(item == r[a]) { // this is true at 1 so 2 is removed, but loop doesn't execute 
       return false; 
      } else { 
       return item; 
      } 
     } 
    } 

    var v = arr.filter(function(item,index,array) { 
    debugger; 
    return argScope(item); // call a function for the scope 

    }); 
    return v; 
} 

destroyer([1, 2, 3, 1, 2, 3], 2, 3); // function call 

help?

回答

0

這應做到:

function destroyer(arr) { 
 

 
    function argScope(item) { 
 
    debugger; 
 
    for (var a = 1; a < arr.length; a++) 
 
     if (item == arr[a]) return false; 
 
    return true; 
 
    } 
 

 
    return arr[0].filter(function(item) { 
 
    debugger; 
 
    return argScope(item); // call a function for the scope 
 
    }); 
 
} 
 

 
var myArray = [1, 2, 3, 1, 2, 3]; 
 
var filteredArray = destroyer([myArray, 2, 3]); 
 

 
console.log(filteredArray);

+0

我做了這個代碼,但我們的區別是括號,不知道這工作,但我想問爲什麼這不適用大括號? – learningjavascriptks

+1

我假設你正在討論for循環中的大括號?它當然會和大括號一起工作,但是你在else子句中返回了這個項目;循環結束後我返回true。 –

3

剛剛一次迭代後,您從循環中返回。 也許你的意思是:

for(var a =1; a<=p; a++) { // start iterate at 1, 0 is the initial array I want to remove elements 
    if(item == r[a]) { // r and a is not set, value is only set after 
     return item; 
    } 
} 
return false;