我正在建立一个游戏评论网站,我的朋友帮助我提出了一个条件声明,确定游戏是否趋向流行,然后显示是否流行。事情是我不知道情况意味着什么。
<script>
$.getJSON('/getgames').then(function (games) {
games.forEach((game) => {
if (game.trending == 1) {
$('#games').append(`<div class="col s4">
<div class="card home-card">
<div class="card-image">
<a href="/game/${game.game_Id}">
<img src="${game.thumbnail}" width="260">
</a>
</div>
<div class="card-content">
<span class="card-title">${game.title}</span>
<p>${game.description}</p>
</div>
<div class="card-action">
<a href="/game/${game.game_Id}">Read More</a>
</div>
</div>
</div>`);
}
});
});
</script>
答案 0 :(得分:0)
因此games
是一个可迭代的对象数组。每个game
对象都有一个trending
属性,可使用game.trending
访问。在循环内,if
语句检查值是否为1
。
尽管如此,代码最好改写为:
// Example array
const games = [
{title:"foo", trending:1, game_Id:12, thumbnail:'//placehold.it/260x50/0bf', description:"aaa"},
{title:"bar", trending:0, game_Id:13, thumbnail:'//placehold.it/260x50/f0b', description:"bbb"},
{title:"baz", trending:1, game_Id:14, thumbnail:'//placehold.it/260x50/b0f', description:"ccc"}
];
// Template for single game
const template_game = (game) => `
<div class="col s4">
<div class="card home-card">
<div class="card-image">
<a href="/game/${game.game_Id}">
<img src="${game.thumbnail}" width="260">
</a>
</div>
<div class="card-content">
<span class="card-title">${game.title}</span>
<p>${game.description}</p>
</div>
<div class="card-action">
<a href="/game/${game.game_Id}">Read More</a>
</div>
</div>
</div>
`;
// Get only trending games
const trendingGames = games.filter(game => game.trending == 1);
// Construct HTML for all trending games
const trendingGamesHTML = trendingGames.map(template_game).join('');
// Append only once
$('#games').append(trendingGamesHTML);
<div id="games"></div>
<script src="//code.jquery.com/jquery-3.1.0.js"></script>
了解详情:
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
答案 1 :(得分:0)
它指出: