var k = 0;
var arr = [1,2,3,4,5,6];
var len = arr.length;
while (k < len && !(k in arr)) {
k++;
}
摘自
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;
};
}
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
好吧,原来是源码抽取来的,应该是为了找到
arr中第一个值的索引比如
因为把
arr[0]删掉了,arr中第一个数字的索引值就变成1了,此时k = 1了因为当
arguments.length != 2的时候,意味着用户没提供reduce的初始值,所以就要找到
arr中的第一个有效值arr[k]赋给value作为初始值题主你提供这个版本的实现应该是有
bug的,你自己试一下把你的Array.prototype.reduce实现复制进console,然后输入以下代码然后就会发现,当
arguments.length == 3时,reduce是会忽略你提供的初始值的