You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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"

调整说明

  1. 在链式调用最前面添加return,将处理结果作为函数返回值,解决undefined问题
  2. 使用reduce回调的第四个参数currentArr拿到当前正在遍历的数组,通过判断index是否等于数组最后一个下标currentArr.length - 1,来决定是否拼接, ,解决末尾多余符号的问题。

内容的提问来源于stack exchange,提问作者DaShaman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 16:45:04