JavaScript 为Array.prototype.reduce()方法实现polyfill

JavaScript 为Array.prototype.reduce()方法实现polyfill

在本文中,我们将学习如何为 Array.prototype.reduce() 方法在JavaScript中实现一个polyfill

polyfill是一段计算机代码,用于在浏览器中实现尚不支持的功能。 这可能是因为您正在使用的浏览器版本较旧,或者新版本的浏览器没有该功能。

我们将讨论JavaScript中数组支持的reduce()方法,并实现我们自己的版本。 reduce()方法逐个调用数组的每个元素上的回调函数,称为reducer函数,并返回一个单个值作为输出。

示例:

JavaScript

<script> 
    const arr = [1, 2, 3, 4]; 
  
    // Find sum of array elements 
    // using reduce method 
    const sum = arr.reduce((total, num) => total + num); 
  
    console.log(sum); 
</script>

输出:

10

Array.prototype.reduce(): 让我们创建一个简单的polyfill来模拟reduce()方法。

示例:

  • 我们创建了一个“myReduce”原型方法,以与reduce()方法相同的方式工作。
  • myReduce()方法接受两个参数,一个回调函数和一个初始值。
  • 我们遍历所有数组元素。
  • 我们检查初始值是否存在,如果存在,我们将回调函数应用于累加器和数组元素,并将结果存储在累加器中;否则,我们用数组元素初始化累加器。
  • 我们将累加器作为最终结果返回。

Javascript

<script> 
    Array.prototype.myReduce = function (callback, initialValue) { 
  
        // Variable that accumulates the result 
        // after performing operation one-by-one 
        // on the array elements 
        let accumulator = initialValue; 
  
        for (let i = 0; i < this.length; i++) { 
              
            // If the initialValue exists, we call 
            // the callback function on the existing 
            // element and store in accumulator 
            if (accumulator) { 
                accumulator = callback.call(undefined,  
                    accumulator, this[i], i, this); 
                  
                // If initialValue does not exist,  
                // we assign accumulator to the 
                // current element of the array 
            } 
            else { 
                accumulator = this[i]; 
            } 
        } 
  
        // We return the overall accumulated response 
        return accumulator; 
    } 
  
    // Code to calculate sum of array elements 
    // using our own reduce method 
    const arr = [1, 2, 3, 4]; 
    console.log(arr.myReduce((total, elem) => total + elem)); 
  
    // Code to calculate multiplication of all array elements 
    console.log(arr.myReduce((prod, elem) => prod * elem)); 
</script>

输出:

10
24

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程