【发布时间】:2017-12-15 21:02:26
【问题描述】:
为冗长的帖子提前道歉。我正在尝试了解 MDN 提供的 array 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;
}
});
}
问题1:如果您看到第1步,
var o = Object(this);
通过将数组传递给 polyfill 方法,我检查了 o 和 this 的两个值。 o 和 this 没有区别。它们都是具有相同数组值的数组(array.isarray 在两者上都返回 true)。为什么不用下面代替..?
var o = this;
问题2:第2步
var len = o.length >>> 0;
上面的行似乎右移了 o.length(32 位)。但是移位的位数是 0。那么我们通过移位 0 位有什么好处...为什么不使用下面的代替...?
var len = o.length;
问题3: else里面的第一个while条件如下
while (k < len && !(k in o)) {
k++;
}
最初 k 设置为 0 并且它似乎总是存在于 o 中。所以这个while循环条件永远不会为真。那么为什么我们需要这个 while 循环,如果它永远不会进入。
【问题讨论】:
标签: javascript arrays polyfills