推荐关注
Meteor
JSLint - a JavaScript code quality tool
jsFiddle
D3.js
WebStorm
推荐书目
JavaScript 权威指南第 5 版
Closure: The Definitive Guide
rain0002009

reduce polyfill 看不太懂

  •  
  •   rain0002009 · Aug 19, 2016 · 2756 views
    This topic created in 3554 days ago, the information mentioned may be changed or developed.
    if (!Array.prototype.reduce) {
      Array.prototype.reduce = function(callback /*, initialValue*/) {
        'use strict';
        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');
        }
        var t = Object(this), len = t.length >>> 0, k = 0, value;
        if (arguments.length == 2) {
          value = arguments[1];
        } else {
          while (k < len && !(k in t)) {
            k++;
          }
          if (k >= len) {
            throw new TypeError('Reduce of empty array with no initial value');
          }
          value = t[k++];
        }
        for (; k < len; k++) {
          if (k in t) {
            value = callback(value, t[k], k, t);
          }
        }
        return value;
      };
    }
    

    网上找的一个数组 reduce 方法的 polyfill 方法,求大神解释一下

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

    这里的意义,怎么感觉好像无法进入分支啊 在下面这个网站上看到的
    https://msdn.microsoft.com/library/ff679975%28v=vs.94%29.aspx?f=255&MSPPError=-2147217396

    4 replies    2016-08-20 11:15:28 +08:00
    7sDream
        1
    7sDream  
       Aug 19, 2016
    那个循环是用来判断数组里的空位的吧:

    TomIsion
        2
    TomIsion  
       Aug 19, 2016
    @7sDream 说的没有错

    ```
    while (k < len && !(k in t)) {
    k++;
    }
    if (k >= len) {
    throw new TypeError('Reduce of empty array with no initial value');
    }
    value = t[k++];
    ```

    这里主要是将数组第一个非 undefined 值初始化 value
    jprovim
        3
    jprovim  
       Aug 20, 2016
    我想顺便提及一下

    `>>>` 是 bit shift, 而且是取正数

    > 1 >> 4
    0
    > -1 >> 4
    -1
    > 1 >>> 4
    0
    > -1 >>> 4
    268435455
    >


    Reference: http://stackoverflow.com/a/10382137/2305243
    rain0002009
        4
    rain0002009  
    OP
       Aug 20, 2016
    @7sDream 还有空位这茬,原来如此
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5524 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 49ms · UTC 08:22 · PVG 16:22 · LAX 01:22 · JFK 04:22
    ♥ Do have faith in what you're doing.