在 JavaScript 中實現 Array.prototype.reduce() 方法的 polyfill


Polyfill 是一種使用使用者定義的方法擴充套件瀏覽器功能的概念。如果使用者的瀏覽器沒有更新,可能會發生瀏覽器不支援任何程式語言(例如 JavaScript)的較新功能的情況。

作為開發者,我們需要檢查瀏覽器是否支援該功能,如果不支援,則需要呼叫使用者定義的方法。

在本教程中,我們將討論為 array.reduce() 方法實現 polyfill。如果任何瀏覽器不支援 array.reduce() 方法,我們將呼叫使用者定義的 reduce() 方法。

在我們開始本教程之前,讓我們瞭解 reduce() 方法的作用。reduce() 方法將陣列簡化為單個元素。例如,我們可以使用 array.reduce() 方法查詢陣列中所有元素的總和,因為我們將所有陣列元素簡化為單個 sum 變數。此外,我們可以使用 reduce() 方法將陣列中的所有字串連線成單個字串。

語法

使用者可以遵循以下語法來實現 array.reduce() 方法的 polyfill。

Array.prototype.reduce = function (callbackFunc, initial) {
   
   // implement logic for reduce() method
} 

在上面的語法中,我們將 reduce() 方法新增到 Array 物件的原型物件。我們需要在函式內部實現 reduce() 方法的邏輯。

示例(使用內建 reduce() 方法)

在下面的示例中,我們建立了一個數字陣列,並使用 reduce() 方法獲得所有陣列元素的總和。使用者可以觀察我們如何將陣列簡化為單個元素。

<html>
<body>
   <h2>Using the <i> reduce() method without polyfill </i> in JavaScript</h2>
   <div id = "content"> </div>
   <script>
      let content = document.getElementById('content');
      function callback(sum, value) {
         return sum + value;
      }
      let array = [30, 50, 6, 7, 8, 9, 50, 3, 2, 3, 43, 5, 4, 3, 23, 32, 456];
      let sum = array.reduce(callback, 0);
      content.innerHTML += "The array values are " + array + "<br>";
      content.innerHTML += "The sum of all array elements using the array.reduce() method is " + sum + "<br>";
   </script>
</body>
</html>

實現 reduce() 方法的 polyfill

使用者應遵循以下步驟來實現 array.reduce() 方法的邏輯。

步驟 1 – 建立一個 singleElement 變數並將其初始化為作為引數傳遞的初始值。initial 也是一個可選引數,因此如果使用者沒有將 initial 值作為 reduce() 方法的引數傳遞,它可以是未定義的。

步驟 2 – 使用 for 迴圈遍歷陣列。

步驟 3 – 如果 singleElement 的值為未定義,則將其初始化為陣列的第一個元素。

步驟 4 – 使用 call() 方法為每個陣列元素執行回撥函式,並用回撥函式返回的值替換 singleElement 變數的值。

步驟 5 – for 迴圈迭代完成後,返回 singleElement 變數的值。

示例

在下面的示例中,我們使用 reduce() 方法對陣列元素進行求和,就像上面的示例一樣,但是在這裡我們使用的是使用者定義的 reduce() 方法。

我們遵循上述步驟實現了使用者定義的 reduce() 方法,使用者可以觀察到它與之前的示例產生相同的輸出。

<html>
<body>
   <h2>Using the <i> reduce() method with polyfill </i> in JavaScript</h2>
   <div id = "content"> </div>
   <script>
      let content = document.getElementById('content');
      function callback(sum, value) {
         return sum + value;
      }
      let array = [30, 50, 6, 7, 8, 9, 50, 3, 2, 3, 43, 5, 4, 3, 23, 32, 456];
      Array.prototype.reduce = function (callbackFunc, initial) {
         
         // initial is an optional parameter.
         
         // if initial passed as an argument, initialize the singleElement with the initial value.
         
         // Otherwise, initialize the singleElement with the first value of the array. 
         let singleElement = initial;
         for (let k = 0; k < this.length; k++) {
            if (singleElement) {
               singleElement = callbackFunc.call(null,
               singleElement, this[k], k, this);
            }
            else {
               singleElement = this[k];
            }
         }
         
         // return the single element.
         return singleElement;
      }
      let sum = array.reduce(callback)
      content.innerHTML += "The array values are " + array + "<br>";
      content.innerHTML += "The sum of all array elements using the array.reduce() method is " + sum + "<br>";
   </script>
</body>
</html>

示例

我們在下面的示例中優化了 polyfilled reduce() 方法。我們在 reduce() 方法內部使用了 forEach() 方法來提高迭代效能。此外,我們使用了三元運算子來初始化 start 變數。

此外,我們定義了字串陣列,並使用 array.reduce() 方法將所有陣列元素轉換為單個字串。

<html>
<body>
   <h2>Using the <i> reduce() method with polyfill </i> in JavaScript</h2>
   <div id = "content"> </div>
   <script>
      let content = document.getElementById('content');
      Array.prototype.reduce = function (callbackFunc, start) {
         let array = this;
         array.forEach(value => {
            start = start !== undefined ? callbackFunc(start, value) : value
         })
         return start;
      }
      function callback(finalStr, str) {
         return finalStr + str;
      }
      let strings = [" Hi ", " Users ", "!", " Welcomes ", " to ", " the ", " tutorialspoint's ", " JavaScript ", " blog! "];
      let finalStr = strings.reduce(callback, "")
      content.innerHTML += "The array values: " + strings + "<br>";
      content.innerHTML += "The final string after merging all array values using the array.reduce() method: " + finalStr + "<br>";
   </script>
</body>
</html>

我們學習瞭如何為 array.reduce() 方法實現 polyfill。我們已經看到了兩種不同的實現使用者定義 reduce() 方法的方法。使用者應該使用第二種方法,因為它更短、更易讀且更簡潔。

更新於:2023年2月28日

1K+ 次瀏覽

啟動您的 職業生涯

完成課程後獲得認證

開始學習
廣告
© . All rights reserved.