簡體   English   中英

任何人都可以解釋以下代碼段:

[英]Can anybody explain this snippet of code:

我已經獲得了這段代碼,而我無法獲得r.concat部分,因為concat通常用於整個數組,而不是單個元素。

function doubleOddNumbers(numbers) {
  return numbers.reduce((r, n) => n % 2 ? r.concat(n * 2) : r, [])
}

這是注釋的代碼:

function doubleOddNumbers(numbers) {
  return numbers.reduce( // reduce iterates over numbers and passes an accumulator from iteration to iteration
    (r, n) => // the reducer function called for each element, r is the accumulator, n is the element
      n % 2   // if the element is odd
        ? r.concat(n * 2) // then append its double to the accumulator
        : r   // otherwise return the accumulator unchanged
  , [])       // start with an empty array for the accumulator
}

這是有關reduceconcat的MDN文檔。

我認為誤解來自於reduce的這種用法:

 [1, 2, 3].reduce((a, b) => a + b, 0); // 6

在此示例中,數組b的值,累加器a和初始值0均為數字。 但這不必一定是這樣,累加器和數組值可以具有不同的類型。 如果我們將上面的行更改為:

 [1, 2, 3].reduce((a, b) => a + b, "") // "123"

由於初始累加器為空字符串,第一次執行reduce ,將連接"" + 1 ,這將導致"1"傳遞到下一個reduce步驟。

現在您的情況是,累加器的初始值是一個空數組,因此r將是一個數組,而n是一個數字。 現在,化簡器將返回r本身,或者將n * 2連接到數組,這還將導致將數組傳遞到下一個化簡器步驟。

  [1, 2, 3].reduce((acc, el) => acc.concat(el), []) 

這就是說,顯示的代碼是只是一個完整的missuse .reduce功能。 您無法理解該代碼並不意味着您很愚蠢,而是意味着所顯示的代碼編寫不正確。 我將其寫為:

  numbers
     .filter(n => n % 2) // only.take odd numbers
     .map(n => n * 2) // double them

由於“數字”是一個(數字)數組,因此您可以從Array.reduce函數的規范開始: https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects /陣列/減少

每個reduce的工作方式如下:

arrayToReduce.reduce((memo, currentElement) => { /* operations using the currentElement that return the new memo value */}, initialValue);

怎么了:

  1. 您從內存中的初始值(上面的initialValue)開始,例如一個空數組。

  2. 對於要減少的數組的每個元素(例如,上面的arrayToReduce),執行一個函數,該函數接收當前存儲的值(上面的“ memo”)和數組中的當前元素。 該函數將檢查當前元素並計算一個新的存儲值。 例如,在您的示例中,對於奇數,將數字加倍並將其添加到存儲的數組中,然后返回存儲的數組; 對於偶數,您什么也不做,因此您可以不更改返回存儲的數組。

  3. 該函數返回的最后一個值是reduce操作的最終結果,即包含奇數的數組加倍。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM