数组减少Polyfill说明

gre*_*hap 4 javascript arrays polyfills

为冗长的帖子提前道歉.我想了解MDN提供的数组reduce 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;
        }
      });
    }
Run Code Online (Sandbox Code Playgroud)

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

var o = Object(this);
Run Code Online (Sandbox Code Playgroud)

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

var o = this;
Run Code Online (Sandbox Code Playgroud)

问题 2 :第2步

var len = o.length >>> 0;
Run Code Online (Sandbox Code Playgroud)

上面的线似乎右移o.length(32位).但是,移位的位数是0.那么我们通过移位0位得到什么优势...为什么不用下面的代码......?

var len = o.length;
Run Code Online (Sandbox Code Playgroud)

问题3:第一个while条件在其他内部,如下所示

 while (k < len && !(k in o)) {
    k++;
  }
Run Code Online (Sandbox Code Playgroud)

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

ibr*_*rir 6

问题1:

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

Array.prototype.reduce.call(undefined, function() {});
Run Code Online (Sandbox Code Playgroud)

因此,当访问诸如length的错误之类的属性时,can't access property **** of undefined将不会抛出错误.

注意:上面的示例使用本机reduce,如果未提供对象,则实际会引发错误.

问题2:

要始终具有有效的整数值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
Run Code Online (Sandbox Code Playgroud)

问题3:

处理稀疏数组:

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

arr.reduce(function(acc, v, i) {
  console.log("index:", i);
}, 0);
Run Code Online (Sandbox Code Playgroud)

它不会在所有的指数从去07000000,只有那些真正存在.

  • Re:问题3,你也可以使用`arr = new Array(700000)`然后`arr [1] = someValue`.那么,arr`中的`0将是'false`但是arr`中的`1将是'true`,所以在这种情况下你仍然会得到`k> 0 (2认同)