如何在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
相关产品推荐
相关产品推荐

