【问题标题】:In Javascript, can you use template literals to console.log content from an object while iterating over it? [closed]在 Javascript 中,您可以在迭代对象时使用模板文字来 console.log 内容吗? [关闭]
【发布时间】:2021-05-13 06:41:57
【问题描述】:

所以我学习 JS 还不到 1 周,我一直在努力寻找解决方案,但除了涉及函数和与 JSON.stringify 相关的答案(我不明白)之外,我似乎无法找一个。在迭代这个对象时,我不想使用字符串连接,而是想使用模板文字来显示每个属性的特定信息。这可能吗?

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++) {
  console.log(`${pokemonList.name[i]} ${pokemonList.height[i]}`);
};

【问题讨论】:

  • 嗨,应该是 pokemonList[i].name
  • JSON.stringify() 有什么问题?该方法将其参数转换为JSON,这是它的文本表示。
  • @Andreas 也许 OP 只是想以特定格式打印一些属性

标签: javascript object iteration console.log template-literals


【解决方案1】:

您可以对数组中的每个项目使用 JSON.stringifay:

pokemonList.forEach(item => console.log(JSON.stringify(item)));

【讨论】:

    【解决方案2】:

    你在 for 循环中有一个错误 您应该将 [i] 替换为 pokemontList,而不是 pokemonList 的属性 ${pokemonList[i].name} ${pokemonList[i].height}

    【讨论】:

      【解决方案3】:

      你绝对可以!您只需将pokemonList.name[i] 更改为pokemonList[i].name

      pokemonList 是其中包含元素的那个,因此您使用pokemonList[i] 访问其中的元素,然后pokemonList[i].name 将为您提供该元素的名称属性。

      这里是固定代码:

      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++) {
        console.log(`${pokemonList[i].name} ${pokemonList[i].height}`);
      };

      另一方面,JSON.stringify 会将整个对象打印为字符串,它看起来类似于上面代码中的列表:

      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++) {
        console.log(JSON.stringify(pokemonList[i]));
      };

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-11-19
        • 2020-04-23
        • 2012-08-10
        • 2018-10-31
        • 2014-10-18
        • 2011-06-04
        • 2017-11-26
        • 2013-08-20
        相关资源
        最近更新 更多