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

如何将ES6箭头函数写法的map函数转为ES6之前的格式?

箭头函数版map改写为普通function的正确写法

原ES6箭头函数代码:

const example = spaceships.map((spaceship) => ({
    homePlanet: spaceship.homePlanet,
    color: spaceship.color
}));

你的尝试代码(报错):

const example = spaceships.map(function(spaceship) ({
    homePlanet: spaceship.homePlanet,
    color: spaceship.color
}));

正确写法

有两种常见的正确形式:

  1. 显式使用return和函数体大括号:
const example = spaceships.map(function(spaceship) {
    return {
        homePlanet: spaceship.homePlanet,
        color: spaceship.color
    };
});
  1. 保留括号包裹对象(仍需显式写return):
const example = spaceships.map(function(spaceship) {
    return ({
        homePlanet: spaceship.homePlanet,
        color: spaceship.color
    });
});

错误原因

箭头函数里的(...)是语法糖——当箭头函数要直接返回对象字面量时,用括号包裹避免被解析成函数体的大括号。但普通function声明必须用{}包裹函数体,不能直接跟(...),而且必须显式写出return语句来返回对象,不像箭头函数可以省略return。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 09:30:53