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

在JavaScript中遍历对象数组时,能否使用模板字面量输出对象内容?

当然可行!用模板字面量遍历对象数组的正确姿势

嘿,刚学JS不到一周就能想到用模板字面量替代字符串拼接,这个思路超棒!完全可以实现,而且比字符串拼接清爽太多了~

首先得指出你代码里的一个小问题:你写的pokemonList.name[i]是错误的访问方式。pokemonList是一个数组,得先通过索引i拿到数组里的单个对象,再去访问这个对象的name、height属性,也就是pokemonList[i].name这种写法。

下面给你两种简单的实现方式,都不用字符串拼接,也完全避开你还没理解的JSON.stringify和复杂函数:

方式一:修正后的普通for循环

先把当前遍历到的对象存进变量里,代码更清晰,也避免重复写长表达式:

const pokemonList = [ 
  {name: 'Bulbasur', height: 70, weight: 15.2, type: ['grass','poison']}, 
  {name: 'Charmander', height: 60, weight: 18.7, type: ['fire']}, 
  {name: 'Squirtle', height: 50, weight: 19.8, type: ['water']} 
];

for (let i = 0; i < pokemonList.length; i++) {
  const currentPokemon = pokemonList[i];
  console.log(`${currentPokemon.name} | 身高:${currentPokemon.height}cm | 体重:${currentPokemon.weight}kg | 属性:${currentPokemon.type.join(', ')}`);
}

这里的currentPokemon.type.join(', ')是把属性数组转成逗号分隔的字符串,比手动拼接数组元素方便多了,也很容易理解~

方式二:更简洁的for...of循环

如果你觉得带索引的for循环有点麻烦,for...of是更适合遍历数组的语法,直接拿到每个对象,不用管索引:

const pokemonList = [ 
  {name: 'Bulbasur', height: 70, weight: 15.2, type: ['grass','poison']}, 
  {name: 'Charmander', height: 60, weight: 18.7, type: ['fire']}, 
  {name: 'Squirtle', height: 50, weight: 19.8, type: ['water']} 
];

for (const pokemon of pokemonList) {
  console.log(`${pokemon.name} | 身高:${pokemon.height}cm | 体重:${pokemon.weight}kg | 属性:${pokemon.type.join(', ')}`);
}

这两种方式都用模板字面量${}来插入变量,完全不需要字符串拼接,输出的内容也可以根据你的需求随意调整格式,比如添加分隔符、单位这些,非常灵活。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 06:34:08