Array Reduce Polyfill 说明

Array Reduce Polyfill Explanation

提前致歉post。我试图了解 MDN 提供的数组减少 polyfill。我无法理解 polyfill 中的某些行,请您解释一下。下面是代码

    if (!Array.prototype.reduce) {
      Object.defineProperty(Array.prototype, 'reduce', {
        value: function(callback /*, initialValue*/) {
          if (this === null) {
            throw new TypeError( 'Array.prototype.reduce ' + 
              'called on null or undefined' );
          }
          if (typeof callback !== 'function') {
            throw new TypeError( callback +
              ' is not a function');
          }

          // 1. Let O be ? ToObject(this value).
          var o = Object(this);

          // 2. Let len be ? ToLength(? Get(O, "length")).
          var len = o.length >>> 0; 

          // Steps 3, 4, 5, 6, 7      
          var k = 0; 
          var value;

          if (arguments.length >= 2) {
            value = arguments[1];
          } else {
            while (k < len && !(k in o)) {
              k++; 
            }

            // 3. If len is 0 and initialValue is not present,
            //    throw a TypeError exception.
            if (k >= len) {
              throw new TypeError( 'Reduce of empty array ' +
                'with no initial value' );
            }
            value = o[k++];
          }

          // 8. Repeat, while k < len
          while (k < len) {
            // a. Let Pk be ! ToString(k).
            // b. Let kPresent be ? HasProperty(O, Pk).
            // c. If kPresent is true, then
            //    i.  Let kValue be ? Get(O, Pk).
            //    ii. Let accumulator be ? Call(
            //          callbackfn, undefined,
            //          « accumulator, kValue, k, O »).
            if (k in o) {
              value = callback(value, o[k], k, o);
            }

            // d. Increase k by 1.      
            k++;
          }

          // 9. Return accumulator.
          return value;
        }
      });
    }

问题 1:如果您看到第 1 步,

var o = Object(this);

我通过将数组传递给 polyfill 方法检查了 o 和 this 的值。 o和this没有区别。它们都是具有相同数组值的数组(array.isarray 都返回 true)。为什么不使用下面的..?

var o = this;

问题2:步骤2

var len = o.length >>> 0;

上一行似乎右移了 o.length(32 位)。但是 no.of 位移的位是 0。那么我们通过位移 0 位获得什么优势......为什么不使用下面的......?

var len = o.length;

问题三:else中第一个while条件如下

 while (k < len && !(k in o)) {
    k++;
  }

最初k被设置为0并且它似乎总是存在于o中。所以这个 while 循环条件永远不会为真。那么为什么我们需要这个 while 循环,如果它永远不会进入内部。

问题一:

确保在对象上调用 reduce,因为可以通过 Function#callFunction#apply 甚至绑定 Function#bind:

调用 reduce

Array.prototype.reduce.call(undefined, function() {});

因此,当访问 length 等属性时,不会抛出 can't access property **** of undefined 的错误。

注意:上面的示例使用本机 reduce 如果没有提供对象,它实际上会抛出错误。

问题二:

总是有一个有效的整数值作为 length(即使它不存在):

console.log(5 >>> 0);         // 5
console.log(5.5 >>> 0);       // 5
console.log("5" >>> 0);       // 5
console.log("hello" >>> 0);   // 0
console.log(undefined >>> 0); // 0

问题三:

处​​理稀疏数组:

var arr = [5, 6];
arr[7000000] = 7;

arr.reduce(function(acc, v, i) {
  console.log("index:", i);
}, 0);

它不会遍历从 07000000 的所有索引,只会遍历那些真正存在的索引。

以下方法有效:

var Arr = [1,2,3,4]

 Array.prototype.myreduce = function(callback,initialvale){

    var result ;
    var resultvalue = initialvale
    
    for(var key =0;key<this.length;key++){
     
        var resultvalue =callback(resultvalue,this[key])
        
        }
    
    return resultvalue;
  
  
} 


var customvalued = Arr.myreduce(function(total,value){

    //console.log(total,value)

     if(value%2==0){
        total.push(value)
    } 
    
    return total 
    
},[])

console.log(customvalued)