从数组中获取前6个元素

时间:2019-01-15 21:58:37

标签: javascript html css

我想显示数组中的前6个元素。我正在使用API​​ SELECT JSON_ARRAYAGG(JSON_OBJECT('id',est_res.est_id,'name',est_res.est_name,'advert_groups',(SELECT JSON_ARRAYAGG(JSON_OBJECT('id',adg.adg_id,'name',adg.adg_name)) FROM advert_group adg INNER JOIN estate est_2 ON est_2.est_id = adg.adg_estate WHERE est_2.est_id = est_res.est_id))) FROM (SELECT * FROM estate est LIMIT 1 OFFSET 2) est_res

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

'themoviedb'

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

https://ibb.co/T1S8RqX

4 个答案:

答案 0 :(得分:0)

404错误是由此引起的:

// you're setting the src of the image as 'https://image.tmdb.org/t/p/w500/val1/val2/val3/val4/val5/val6' which doesn't make sense
tvImage.src = img + tvSeriesImg.slice(0, 6);

尝试替换此块:

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);

与此:

tvSeriesImg.slice(0, 6).map((imgUrl) => {
    const tvImage = document.createElement('img');

    // set src = "https://image.tmdb.org/t/p/w500/valx" where '/valx' is the imgUrl.
    tvImage.src = img + imgUrl;
    tvImage.setAttribute('id', 'movieThumb');
    popTvSeriesCard.appendChild(tvImage);
})

希望有帮助!

答案 1 :(得分:0)

这是简化的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)

})

答案 2 :(得分:0)

您正在做的事情非常混乱,无法看到您正在运行的站点并测试代码。但是,我认为您的问题与下半部分有关:

//Get the first 6 items from the array!!
        
        tvSeriesImg.push(results.poster_path);

        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);

您将路径存储在数组中,然后在控制台日志中每次打印出前6个(即使不包含6个)时也会打印出前6个。这有点令人困惑,但假设这是代码。然后你在做

 tvImage.src = img + tvSeriesImg.slice(0, 6);

这将在每次循环时将数组中的前6个元素删除并将其附加到img URL,因此您尝试将包含6个元素的URL作为src添加。因此错误。网址变得像http://img.com/absec.jpg,abb.jpg之类的东西了……

由于我无法测试,因为我没有API密钥,因此可能会出现错误,但是您的代码应如下所示:

var url = "https://api.themoviedb.org/3/tv/popular?api_key=f1d314280284e94ff7d1feeed7d44fdf&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);

    });
    //remove from loop since you only want the top 6
    const tvImage = document.createElement('img');
    var first6Urls = tvSeriesImg.slice(0, 6);
    for (var i = 0; i < first6Urls.length; i++) {
      tvImage.src = img + first6Urls[i]
      tvImage.setAttribute('id', 'movieThumb' + i+1);
      popTvSeriesCard.appendChild(tvImage);
    }
  }
}
request.send();

基本上,您需要为每个循环将提取和附加代码放在您的外部,然后将它们一个接一个地附加。

答案 3 :(得分:-1)

您必须为每个tvSeriesImg值创建一个子img:

{
"AcademicTerms": [
    {
        "TermId": "1988FA",
        "GradePointAverage": 3,
        "Credits": 12,
        "ContinuingEducationUnits": 0,
        "AcademicCredits": [
            {
                "Id": "142757",
                "CourseId": "2242",
                "StudentId": "9999999",
                "SectionId": 1234567,
                "CourseName": "MCOM-3103",
                "Title": "Mass Media Survey",
                "VerifiedGradeId": "10",
                "VerifiedGradeTimestamp": "1988-12-15T16:58:31Z",
                "FinalGradeId": "10",
                "FinalGradeExpirationDate": null,
                "LastAttendanceDate": null,
                "NeverAttended": null,
                "Credit": 3,
                "GpaCredit": 3,
                "GradePoints": 9,
                "AttemptedCredit": 3,
                "CompletedCredit": 3,
                "ContinuingEducationUnits": 0,
                "Status": "New",
                "StatusDate": "1988-08-29T00:00:00",
                "TermCode": "1988FA",
                "Location": null,
                "MidTermGrades": [],
                "GradingType": "Graded",
                "SectionNumber": "",
                "HasVerifiedGrade": true,
                "AdjustedCredit": 3,
                "IsNonCourse": false,
                "IsCompletedCredit": true,
                "ReplacedStatus": "NotReplaced",
                "ReplacementStatus": "NotReplacement",
                "StartDate": "1988-08-29T00:00:00",
                "EndDate": "1988-12-15T00:00:00",
                "AdjustedGpaCredit": 3,
                "StudentCourseSectionId": null
            }
          ]
       }
    ]
}