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

为何设置返回数组的函数仍返回void,报void[]不可赋值给number[]错误

报错根因

map的回调函数使用大括号{}包裹逻辑时没有显式书写return语句,所有遍历项的处理结果都未被返回,最终map输出的是全undefined的void[]类型数组,和预期的number[]类型不匹配。


修正方案

方案1:省略箭头函数大括号(推荐简洁写法)

箭头函数如果只包含单个返回表达式,可以省略大括号,自动返回表达式执行结果:

const option = () => {
    let arr = [200, 400, 800, 1000, 1, 2, 3, 4, 5];
    return arr.map((x, i) => 
      i <= 3 ? x * 3.281 : x / 1.609
    );
}
console.log(option());

方案2:保留大括号,显式添加return语句

如果后续需要在回调内拓展更多逻辑,可以保留大括号,手动返回处理后的值:

const option = () => {
    let arr = [200, 400, 800, 1000, 1, 2, 3, 4, 5];
    return arr.map((x, i) => {
      return i <= 3 ? x * 3.281 : x / 1.609;
    });
}
console.log(option());

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 21:24:00