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

如何在JavaScript中使用forEach遍历对象数组并按指定格式输出?

用JavaScript的forEach方法实现指定格式的甜甜圈信息打印

这事儿用forEach就能轻松搞定,直接遍历数组里的每个对象,按照要求的格式拼接字符串输出就好啦。

完整实现代码

var donuts = [
  { type: "Dairy Milk", cost: 1.22 },
  { type: "Kit Kat", cost: 2.45 },
  { type: "Milky Bar", cost: 1.59 }
];

// 使用forEach遍历数组
donuts.forEach(function(donut) {
  // 用模板字符串拼接成目标格式并打印
  console.log(`${donut.type} cost $${donut.cost} each`);
});

兼容方案说明

如果你的运行环境不支持ES6的模板字符串,换成普通的字符串拼接也完全可以达到效果:

donuts.forEach(function(donut) {
  console.log(donut.type + " cost $" + donut.cost + " each");
});

运行上面的代码后,就会得到你期望的输出:

Dairy Milk cost $1.22 each
Kit Kat cost $2.45 each
Milky Bar cost $1.59 each

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 04:06:21