循环遍历.map方法中的数组

时间:2017-07-24 19:57:36

标签: javascript html arrays

我对JavaScript非常垃圾我想知道是否有人可以提供帮助。

我已经从API中映射了一些数据并将其显示到页面中,我还想循环遍历图像阵列中的图像,这样每张卡片都有不同的图像。

const images = ['https://placeimg.com/200/200/nature','https://placeimg.com/200/200/tech','https://placeimg.com/200/200/animals','https://placeimg.com/200/200/nature','https://placeimg.com/200/200/tech','https://placeimg.com/200/200/animals','https://placeimg.com/200/200/nature','https://placeimg.com/200/200/tech','https://placeimg.com/200/200/animals','https://placeimg.com/200/200/nature'];


function getPeople() {
   const endpoint = "https://swapi.co/api/people/";
   return fetch(endpoint)
      .then(function(blob) {
         return blob.json();
      })
      .then(function(data) {
         return data.results;
      });
}

getPeople().then(peopleObject => { 
    displayPerson(peopleObject)
});

function displayPerson(peopleObject) {
  
      const people = peopleObject.map(person => {
        return `
          <div class="card">
            <p> ${person.name} </p>
            <p> ${person.height}cm </p>
            <p> -- I WANT A IMAGE FROM IMAGE ARRAY HERE -- </p>
          </div>
        `
   }).join('');
  const cardContainer = document.createElement('div');
  cardContainer.className += "card-container";
  cardContainer.innerHTML = people;
  document.body.appendChild(cardContainer);
}

2 个答案:

答案 0 :(得分:2)

您可以在代表Array#map的{​​{1}}函数中使用第二个参数,只需引用index数组中的指定图像。

<强> Codepen

images

答案 1 :(得分:1)

const images = ['https://placeimg.com/200/200/nature','https://placeimg.com/200/200/tech','https://placeimg.com/200/200/animals','https://placeimg.com/200/200/nature','https://placeimg.com/200/200/tech','https://placeimg.com/200/200/animals','https://placeimg.com/200/200/nature','https://placeimg.com/200/200/tech','https://placeimg.com/200/200/animals','https://placeimg.com/200/200/nature'];


function getPeople() {
   const endpoint = "https://swapi.co/api/people/";
   return fetch(endpoint)
      .then(function(blob) {
         return blob.json();
      })
      .then(function(data) {
         return data.results;
      });
}

getPeople().then(peopleObject => { 
    displayPerson(peopleObject)
});

function displayPerson(peopleObject) {
  
      const people = peopleObject.map((person, idx) => {
        return `
          <div class="card">
            <p> ${person.name} </p>
            <p> ${person.height}cm </p>
            <p> <img src = "${images[idx % images.length]}"/></p>
          </div>
        `
   }).join('');
  const cardContainer = document.createElement('div');
  cardContainer.className += "card-container";
  cardContainer.innerHTML = people;
  document.body.appendChild(cardContainer);
}