JS使用filter、sort、reduce处理数字数组返回指定字符串报错如何解决
问题原因
- 返回undefined:你用大括号包裹了箭头函数的函数体,但没有添加
return语句返回链式调用的最终结果,函数默认返回undefined。 - 末尾多余逗号:判断是否为最后一个元素的逻辑错误,
index+1!==undefined恒为真(数字累加不可能得到undefined),所以每一轮都会拼接,后缀,最终末尾自然多余符号。
修复方案
调整后的代码如下,保留了要求的filter、sort、reduce三个方法:
const numSelectString = (numArr) => { // 筛选奇数 return numArr.filter((num) => num % 2 !== 0) // 升序排序 .sort((a,b) => a - b) // 拼接字符串 .reduce((acc, next, index, currentArr) => { // 判断是否是最后一个元素 if (index !== currentArr.length - 1) { return acc + next + ', '; } else { return acc + next; } }, '') } const nums = [17, 34, 3, 12] console.log(numSelectString(nums)) // 输出 "3, 17"
调整说明
- 在链式调用最前面添加
return,将处理结果作为函数返回值,解决undefined问题 - 使用reduce回调的第四个参数
currentArr拿到当前正在遍历的数组,通过判断index是否等于数组最后一个下标currentArr.length - 1,来决定是否拼接,,解决末尾多余符号的问题。
内容的提问来源于stack exchange,提问作者DaShaman
相关产品推荐
相关产品推荐

