2017-08-04 25 views
1

我想了解下面的尋求和摧毀挑戰。尋找和摧毀Freecode陣營挑戰的論點

任務:你將被提供一個初始數組(第一個參數在destroyer函數中),接着是一個或多個參數。從初始數組中刪除與這些參數具有相同值的所有元素。

This is the initial code below: 
function destroyer(arr) { 
    // Remove all the values 
    return arr; 
} 

destroyer([1, 2, 3, 1, 2, 3], 2, 3); 

經過幾次(真的)幾次嘗試,看着其他人的代碼,我能夠解決任務。不過,我認爲這更糟糕。我在下面複製了我的代碼,但我希望有人能爲我澄清一些事情。

  1. 下面的代碼通過了我是否在iterateThroughArray函數內返回val或args。這是爲什麼?

  2. 如果我應該將所有參數與第一個參數進行比較,那麼在這段代碼中,我指出了什麼?我一直認爲我需要拼接第一個參數來比較所有其他參數,或者爲參數[0]創建一個變量。任何指導,您可以提供非常感謝!

function destroyer(arr) { 
 
     var args = Array.from(arguments); //this also converts them to an array 
 
     var iterateThroughArr = function (val) { 
 
     if (args.indexOf(val) ===-1){ 
 
      return args; 
 
      } 
 
     }; 
 
     return arr.filter(iterateThroughArr); 
 
    }

回答

1

這聽起來很多參加,但這裏是我的解釋

function destroyer(arr) { 
 
     var args = Array.from(arguments); //Here arr is converted to [Array(6),2,3] 
 
     //console.log(args) 
 
    /* var iterateThroughArr = function (val) { 
 
     if (args.indexOf(val) ===-1){ 
 
      return args; 
 
      } 
 
     }; 
 
     
 
    return arr.filter(iterateThroughArr); 
 
    */ 
 
     
 
    // to make more clear the above code can be rewritten as below 
 
    var arr = arr.filter(function (val) { 
 
      console.log("args = "+ args + " val = " + val + " indexOf(val) " + args.indexOf(val)) 
 
     // here you are itterating through each arr val which in this case is[1,2,3,1,2,3] 
 
     // if you dont believe me uncomment the next console.log() and see the output 
 
     // console.log(val) 
 
     if (args.indexOf(val) ===-1){ 
 
      // here is where the magic happens 
 
      // Now you are checking if val exisists by using a builtin method called .indexOf() 
 
      // In general, .indexOf() returns -1 if a value does not exist within an array 
 
      //Below is working example 
 
      /* var array = [1,2,3,4,5] 
 
      console.log(array.indexOf(1)) // 0 since it is located at index 0 
 
      console.log(array.indexOf(5)) // 4 since it is located at index 4 
 
      console.log(array.indexOf(10)) // -1 since it does not exisit 
 
      */ 
 
      // Therefore, if value passes the above if statement 
 
      //then that means it doesnot exisit on args([Array(6),2,3]) 
 
      //which as a result will be included on the filtered array 
 
      
 
      return args; 
 
      } 
 
     }); 
 
     
 
     return arr; 
 
     
 
    } 
 
    
 
    
 
var val = destroyer([1, 2, 3, 1, 2, 3], 2, 3); 
 
//console.log(val)

基本上,你需要了解的是什麼過濾器是如何工作的nd .index如何工作。 更多細節請訪問Mozilla的文檔:.indexOf().filter()

+0

讓我知道如果您有任何顧慮 – dawit

+0

太感謝你了!這很棒! 1後續問題:indexOf只能用於數組,還是可以與字符串一起使用? – Veronica