我想reduce自己写.但在过去的4个小时里,我做不到.
var a = [10, 21, 13, 56];
function add(a, b) { return a + b }
function foo(a, b) { return a.concat(b) }
Array.prototype.reduce2 = function () {
// I do not understand how to handle the function of the inlet
// I know that I should use arguments, but I don't know how many arguments there will be
var result = 0;
for(var i = 0; i < arguments.length; i++) {
result += arguments[i];
}
return result;
};
console.log(a.reduce(add), a.reduce2(add)) // 100 100
console.log(a.reduce(add, 10), a.reduce2(add, 10)) // 110 110
Run Code Online (Sandbox Code Playgroud)
是的,我知道这似乎是很多话题,但我找不到答案.我错过了什么,或者在这里做错了什么?
subject中的数组不作为参数传递,而是context(this).
您还需要区分起始值的存在与否:
var a = [10, 21, 13, 56];
function add(a, b) { return a + b }
function foo(a, b) { return a.concat(b) }
Array.prototype.reduce2 = function (f, result) {
var i = 0;
if (arguments.length < 2) {
i = 1;
result = this[0];
}
for(; i < this.length; i++) {
result = f(result, this[i], i, this);
}
return result;
};
console.log(a.reduce(add), a.reduce2(add)) // 100 100
console.log(a.reduce(add, 10), a.reduce2(add, 10)) // 110 110
// extra test with foo:
console.log(a.reduce(foo, 'X'), a.reduce2(foo, 'X')) // X10211356 X10211356Run Code Online (Sandbox Code Playgroud)
根据你的代码
var a = [10, 21, 13, 56];
function add(a, b) { return a + b }
function foo(a, b) { return a.concat(b) }
Array.prototype.reduce2 = function(fn, start){
var result = start !== undefined ? start : this[0];
for (var i = 0; i < this.length; i++) {
result = fn(result, this[i]);
}
return result;
};
console.log(a.reduce(add), a.reduce2(add)) // 100 100
console.log(a.reduce(add, 10), a.reduce2(add, 10)) // 110 110
console.log(a.reduce(foo, ''), a.reduce2(foo, ''));
console.log(a.reduce(foo, 'X'), a.reduce2(foo, 'X'));Run Code Online (Sandbox Code Playgroud)