数组返回正确的结果。但在HTML显示中显示未定义

时间:2017-11-21 00:15:16

标签: javascript jquery html arrays

我正在处理我正在进行的项目的问题。我正在使用API​​来返回视频游戏所在的平台数组。数组返回正确的结果,但是我在HTML中显示这些值时遇到问题。结果只显示未定义。

Website preview gamePlatform console log results

// Renders platform information for each game 
const renderPlatformInfo = function (platformResult) {
const gamePlatform = [];

for (let i = 0; i <= `${platformResult.length - 1}`; i++) {
  let getPlatforms = gamePlatform.push(platformResult[i].name);
}

gamePlatform.forEach(function (platformItem) {
  $('.platforms').append(`<li>${platformItem}</li>`)
});

console.log(gamePlatform); 

};

// Renders game information for the searched game
const renderGameInfo = function (gameInfoResult) {
return `<div class="js-game-data row">
                <h2 class="game-name col-12">${gameInfoResult.name}</h2>
                <img src="${gameInfoResult.image.medium_url}" class="game-image col-4" alt="Box art for ${gameInfoResult.name}">
                <ul class="platforms col-6">
                <h3 class="col-12">Original release date:</h3>${gameInfoResult.original_release_date}
                <h3>Platforms:</h3>
                ${renderPlatformInfo(gameInfoResult.platforms)}
                </ul>
                <p class="game-description col-6">${gameInfoResult.deck} <br> <br> <span class="game-details col-12"><b>For more details about the game: <a href="${gameInfoResult.site_detail_url}" target="_blank">Click Here</a></b></span></p>
            </div>
        `;
}

2 个答案:

答案 0 :(得分:1)

renderPlatformInfo 应该返回一些内容。你错过了那里的回归吗?

答案 1 :(得分:1)

renderPlatformInfo无法将子元素附加到尚不存在的DOM元素。它试图选择的UL在您尝试追加时不会呈现。此外,由于renderPlatformInfo不会返回任何内容,因此它始终会在模板文字中评估为undefined。如果在renderPlatformInfo中返回HTML字符串,则代码应该有效。尝试类似:

let str = '';
gamePlatform.forEach(function(platformItem){
  str += `<li>${platformItem}</li>`;
});
return str;