为何reduce()生成的拼接字符串开头无逗号?
为什么reduce拼接字符串没有开头逗号?
核心原因:未指定reduce的初始值
你调用reduce()时没传第三个参数(初始值),这会让reduce默认把数组第一个元素作为初始的total,然后从第二个元素开始执行回调。
你的代码执行流程拆解:
- 第一次迭代:
total = "banana",item = "melon"→ 返回"banana, melon" - 第二次迭代:
total = "banana, melon",item = "apple"→ 返回"banana, melon, apple" - 后续迭代依次拼接,最终结果自然不会以逗号开头。
解决方法:传入初始值
给reduce()加上初始值空字符串,就能让第一个元素也被加上前置逗号:
let fruits = ["banana", "melon", "apple", "orange", "peach"]; // 加初始值"",并调整拼接符匹配你的预期格式 let returnStatement = fruits.reduce((total, item) => { return total + "," + item; }, ""); console.log(returnStatement); // 输出:,banana,melon,apple,orange,peach
如果需要保留元素间的空格,改成return total + ", " + item即可,结果会是, banana, melon, apple, orange, peach。
内容的提问来源于stack exchange,提问作者Joss
相关产品推荐
相关产品推荐

