reduce polyfill 看不太懂

2016-08-19 17:23:04 +08:00
 rain0002009
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

2324 次点击
所在节点    JavaScript
4 条回复
7sDream
2016-08-19 17:36:32 +08:00
那个循环是用来判断数组里的空位的吧:

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
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
2016-08-20 11:15:28 +08:00
@7sDream 还有空位这茬,原来如此

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/300475

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX