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

如何为数组中每个对象的username字段添加感叹号

问题原因

你得到['[object Object]!']是因为forEach回调里的参数是数组中的整个对象,不是username属性。当你把对象和字符串'!'拼接时,JavaScript会把对象转换成默认的字符串表示[object Object],所以最终得到了错误的结果。

修正后的代码

方式一:修正forEach的写法

把回调参数改为代表数组元素的对象(比如命名为user),然后访问它的username属性再拼接'!':

const array = [
  { username: "john", team: "red", score: 5, items: ["ball", "book", "pen"] },
  { username: "becky", team: "blue", score: 10, items: ["tape", "backpack", "pen"] },
  { username: "susy", team: "red", score: 55, items: ["ball", "eraser", "pen"] },
  { username: "tyson", team: "green", score: 1, items: ["book", "pen"] },
];

const players = [];
array.forEach((user) => {
  players.push(user.username + '!');
});
console.log(players); // 输出: ["john!", "becky!", "susy!", "tyson!"]

方式二:用map更高效(推荐)

如果是要从原数组生成新数组,map方法比forEach更合适,它会直接返回处理后的新数组,不需要额外声明空数组:

const array = [
  { username: "john", team: "red", score: 5, items: ["ball", "book", "pen"] },
  { username: "becky", team: "blue", score: 10, items: ["tape", "backpack", "pen"] },
  { username: "susy", team: "red", score: 55, items: ["ball", "eraser", "pen"] },
  { username: "tyson", team: "green", score: 1, items: ["book", "pen"] },
];

const players = array.map(user => user.username + '!');
console.log(players); // 输出: ["john!", "becky!", "susy!", "tyson!"]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 10:50:41