为什么在 reduce() 创建的数组的开头没有逗号?



由于代码中的特殊原因,我使用了Reduce函数。事实上,我从某个地方拿走了代码,有一点我无法理解。希望你能帮我解决那个问题。

我的代码是这样的:

let fruits = ["banana", "melon", "apple", "orange", "peach"];
let returnStatement = fruits.reduce((total, item) => {
return total + ", " + item;
});
console.log(returnStatement);

在这一点上,我很好奇为什么reduce函数没有在log语句的开头放逗号。让我告诉你我的意思。

我期待这个声明:

',banana, melon, apple, orange, peach' 

我知道reduce在过程结束时只会输出一件事。在这里它输出字符串。

为什么它不把逗号放在字符串的开头?

MDN文档中有解释:

如果指定了initialValue,也会导致currentValue初始化为数组中的第一个值。如果未指定initialValue,则previousValue初始化为数组中的第一个值,currentValue初始化为阵列中的第二个值。

请参阅下面的示例,一次使用空字符串的初始值,一次用您的变体:

const fruits  =["banana","melon","apple","orange","peach"];
const resultWithoutInitialValue = fruits.reduce((total,  item) => {
return total + ", " + item;      
});
const resultWithInitialValue = fruits.reduce((total,  item) => {
return total + ", " + item;      
}, "");
console.log(resultWithoutInitialValue);
console.log(resultWithInitialValue);

最新更新