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

JavaScript中.map()迭代器可搭配匿名函数使用吗?附代码返回undefined问题

问题原因

你的代码运行后返回undefined的核心原因是:你定义的squareNums函数没有显式返回map方法的执行结果。JavaScript中没有写return语句的函数,默认返回值为undefined。
你传入map的匿名函数本身逻辑是正确的,map方法执行后已经生成了平方后的新数组,只是你没有把这个数组作为squareNums的返回值传出来,所以拿到的是undefined。

修复代码

const numbers = [2, 7, 9, 171, 52, 33, 14]

const toSquare = num => num * num

// 修复写法1:保留原有匿名函数,新增return返回map结果
function squareNums(numArr) {
  return numArr.map(num => {
    return num ** 2
  })
}

// 修复写法2:直接复用已经定义好的toSquare函数,不需要额外写匿名函数
function squareNums(numArr) {
  return numArr.map(toSquare)
}

const numberArray = squareNums(numbers);
console.log(numberArray); // 输出:[4, 49, 81, 29241, 2704, 1089, 196]

补充说明

map和匿名函数配合的逻辑非常直接:map会遍历原数组的每一个元素,依次将元素作为参数传入你写的匿名函数,函数的返回值会被依次收集,最终组成一个新数组返回。你只需要保证把这个新数组从你的外层函数返回即可拿到结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 05:54:03