JavaScript - Array .reduceRight() 方法



在 JavaScript 中,Array.reduceRight() 方法將一個函式應用於累加器和陣列中的每個元素(從右到左),以將其歸約為單個值。

此方法不會為空陣列元素執行 reducer 函式。此外,它不會修改原始陣列。

注意 - 如果當前陣列為空或不包含任何 initialValue,此方法將丟擲'TypeError'異常。

reduce() 和 reduceRight() 之間的區別

reduce() 和 reduceRight() 方法幾乎相同,但它們之間存在細微差別。reduce() 方法從左到右迭代陣列,而 reduceRight() 方法從右到左迭代陣列。

語法

以下是 JavaScript Array.reduceRight() 方法的語法:

reduceRight(callbackFn(accumulator, currentValue, currentIndex, array), initialValue)

引數

  • callbackFn - 這是要在陣列的每個元素上執行的函式。此函式接受四個引數
    • accumulator - 這是 initialValue,或函式先前返回的值。
    • currentValue - 這是陣列中正在處理的當前元素。如果指定了 initialValue,則其值為最後一個元素,否則其值為倒數第二個元素。
    • currentIndex (可選) - 這是陣列中正在處理的當前元素的索引。
    • array (可選) - 這是呼叫 reduce() 方法的陣列。
  • initialValue (可選) - 當第一次呼叫回撥函式時,累加器引數初始化的值。

返回值

此方法返回單個值,該值是縮減陣列後的結果。

示例

示例 1

在下面的示例中,reduceRight() 將陣列元素從末尾加到開頭,從最後一個元素開始,並使用累加器的初始值。

<html>
<body>
   <script>
      const numbers = [10, 20, 30, 40, 50];
      const sum = numbers.reduceRight((accumulator, currentValue) => accumulator + currentValue, 0);
      document.write(sum);
   </script>
</body>
</html>

輸出

150

示例 2

在此示例中,reduceRight() 方法從陣列的最後一個元素 (50) 和一個空陣列作為累加器開始。它從右到左迭代,將每個元素推入累加器。

<html>
<body>
   <script>
      const numbers = [10, 20, 30, 40, 50];
      const reversedNumbers = numbers.reduceRight((accumulator, currentValue) => {
         accumulator.push(currentValue);
         return accumulator;
      }, []);
      document.write(reversedNumbers);
   </script>
</body>
</html>

輸出

50,40,30,20,10

示例 3

在這裡,reduceRight() 方法從最後一個巢狀陣列 ([5, 6]) 和一個空陣列作為累加器開始。它從右到左迭代,將每個陣列連線到累加器。

<html>
<body>
   <script>
      const arrays = [[1, 2], [3, 4], [5, 6]];
      const flattenedArray = arrays.reduceRight((accumulator, currentValue) => accumulator.concat(currentValue), []);
      document.write(flattenedArray);
   </script>
</body>
</html>

輸出

5,6,3,4,1,2

示例 4

如果當前陣列不包含任何元素(沒有可用的初始值),則 reduce() 方法將丟擲“TypeError”異常。

<html>
<body>
   <script>
      const numbers = [];
      try {
         numbers.reduce((accumulator, currentValue) => accumulator * currentValue);
      } catch (error) {
         document.write(error);
      }
   </script>
</body>
</html>

輸出

TypeError: Reduce of empty array with no initial value
廣告