
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
1 7sDream 2016-08-19 17:36:32 +08:00 那个循环是用来判断数组里的空位的吧: |
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 |
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 |
4 rain0002009 OP @7sDream 还有空位这茬,原来如此 |