首页 > 解决方案 > 从数组中获取前 6 个元素

问题描述

我想显示数组中的前 6 个元素。我正在使用 API 'themoviedb'

我正在从 API 获取数据并将数据存储在数组中。

var url = "https://api.themoviedb.org/3/tv/popular?api_key=YOURKEY&language=en-US&page=1";
var img  = "https://image.tmdb.org/t/p/w500"
var tvSeriesImg = [];

var request = new XMLHttpRequest();     // New instance of XMLHttpRequest
request.open('GET', url, true);         // Open the connection using the 'GET' Method
request.onload = function(){          // Create an onload function this is where the data is displayed on the webpage

var data = JSON.parse(this.response);    // Creating a data variable where our JSON is parsed and stored.

if(request.status >= 200 && request.status < 400){      // Check the request status.

    data.results.forEach(results => {                   //Looping through the JSON Array

        const popTvSeries = document.getElementById('tv-series-data');
        const popTvSeriesCard = document.createElement('div');
        popTvSeriesCard.setAttribute('id', 'card');
        popTvSeries.appendChild(popTvSeriesCard);

        tvSeriesImg.push(results.poster_path);

        //Get the first 6 items from the array!!
        console.log(tvSeriesImg.slice(0, 6));
        const tvImage = document.createElement('img');
        tvImage.src = img + tvSeriesImg.slice(0, 6);
        tvImage.setAttribute('id', 'movieThumb');
        popTvSeriesCard.appendChild(tvImage);
    });
}

}

request.send();  

我曾尝试使用 slice 方法,但出现以下错误:

https://ibb.co/T1S8RqX

标签: javascripthtmlcss

解决方案


这是一个简化的 forEach 可以解决您的问题。

const cards = document.getElementById('tv-series-data')

results.forEach(result => {

  const card = document.createElement('div')
  card.id = result.id // ID's should be unique

  card.innerHTML = `<img src="${img}${result.poster_path}">`
  cards.appendChild(card)

})

推荐阅读