V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐关注
Meteor
JSLint - a JavaScript code quality tool
jsFiddle
D3.js
WebStorm
推荐书目
JavaScript 权威指南第 5 版
Closure: The Definitive Guide
rain0002009
V2EX  ›  JavaScript

reduce polyfill 看不太懂

  •  
  •   rain0002009 · 2016-08-19 17:23:04 +08:00 · 2302 次点击
    这是一个创建于 2819 天前的主题,其中的信息可能已经有所发展或是发生改变。
    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 条回复    2016-08-20 11:15:28 +08:00
    7sDream
        1
    7sDream  
       2016-08-19 17:36:32 +08:00
    那个循环是用来判断数组里的空位的吧:

    TomIsion
        2
    TomIsion  
       2016-08-19 17:46:42 +08:00
    @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  
       2016-08-20 04:07:00 +08:00
    我想顺便提及一下

    `>>>` 是 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
       2016-08-20 11:15:28 +08:00
    @7sDream 还有空位这茬,原来如此
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3977 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 10:34 · PVG 18:34 · LAX 03:34 · JFK 06:34
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.