reduce 未提供时如何确定其初始值?
How does reduce decide its initial value, when it's not provided?
javascript 的 reduce
函数在未传递时如何确定其初始值?它只是默认为数字 0
吗?
为什么这两个工作:
[1, 2, 3, 4].reduce((sum, currentValue) => {
return sum + currentValue;
});
[1, 2, 3, 4].reduce((string, currentValue) => {
return `${string}` + currentValue;
});
但这不是吗?
[1, 2, 3, 4].reduce((object, currentValue) => {
object[currentValue] = currentValue;
return object;
});
Array.prototype.reduce()
初始值(可选)
Value to use as the first argument to the first call of the callback. If no initial value is supplied, the first element in the array will be used. Calling reduce() on an empty array without an initial value is an error.
javascript 的 reduce
函数在未传递时如何确定其初始值?它只是默认为数字 0
吗?
为什么这两个工作:
[1, 2, 3, 4].reduce((sum, currentValue) => {
return sum + currentValue;
});
[1, 2, 3, 4].reduce((string, currentValue) => {
return `${string}` + currentValue;
});
但这不是吗?
[1, 2, 3, 4].reduce((object, currentValue) => {
object[currentValue] = currentValue;
return object;
});
Array.prototype.reduce()
初始值(可选)
Value to use as the first argument to the first call of the callback. If no initial value is supplied, the first element in the array will be used. Calling reduce() on an empty array without an initial value is an error.