【问题标题】:How to display same property from different objects in Javascript如何在Javascript中显示来自不同对象的相同属性
【发布时间】:2020-10-07 10:42:38
【问题描述】:

我正在做一个使用 The Movie Db API 的项目,但我对显示以下对象有点困惑:

(3) [{…}, {…}, {…}]
0: {id: 12, name: "Adventure"}
1: {id: 28, name: "Action"}
2: {id: 878, name: "Science Fiction"}
length: 3
__proto__: Array(0)

基本上,我想弄清楚如何在一个元素中显示这 3 种类型。像这样执行 forEach 循环:

const genreArr = data.genres;
console.log(genreArr)
genreArr.forEach(function(item){
    genre.textContent = item.name;
})

只显示一个流派名称,而不是全部。 那么,我需要做什么才能在一个段落中显示所有这些内容?

【问题讨论】:

  • 你正在用下一个流派覆盖上一个流派,考虑使用+=,或者更好的是,累积一个字符串,然后在完成后设置它以避免多次更新dom

标签: javascript arrays object foreach


【解决方案1】:

genre.textContent = item.name; 这一行将覆盖textContent 的每次迭代forEach,只留下最后一个值。

您需要使用+= 附加到textContent

const genreArr = [
  {id: 12, name: "Adventure"},
  {id: 28, name: "Action"},
  {id: 878, name: "Science Fiction"}
];

const genre = document.getElementById('genre');

genreArr.forEach(function(item){
    genre.textContent += item.name + ' | ';
})
<div id="genre">

</div>

使用map()join() 的另一种更有效的方法:

const genreArr = [
  {id: 12, name: "Adventure"},
  {id: 28, name: "Action"},
  {id: 878, name: "Science Fiction"}
];

const genre = document.getElementById('genre');

/* Create an array containing only the 'name' values */
var genreNames = genreArr.map(function(item) {
  return item['name'];
});

/* Assign the names to the div in one go, with a seperator */
genre.textContent = genreNames.join(' | ');
&lt;div id="genre"&gt;&lt;/div&gt;

【讨论】:

    【解决方案2】:

    您可以使用map轻松操作

    const arraryList = [{id: 12, name: "Adventure"},
    {id: 28, name: "Action"},
    {id: 878, name: "Science Fiction"}];
    
    const output = arraryList.map(val => val.name);
    const combinedName = output.join(",");
    console.log(output);
    console.log(combinedName);

    【讨论】:

      【解决方案3】:

      你可以这样做

      let arr = [];
      let sentence = '';
      
      genreArr.forEach(el => {
        arr.push(el.name);
        sentence += ' ' + el.name;
      })
      
      console.log(arr)
      console.log(sentence)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-12
        • 1970-01-01
        • 2016-01-04
        • 2020-07-13
        • 2019-03-04
        • 1970-01-01
        相关资源
        最近更新 更多