这个条件声明意味着什么?

问题描述 投票:-2回答:2

我正在建立一个游戏评论网站,我的朋友帮我提出了一个条件声明,以决定游戏是否趋势,然后显示它们是否存在。问题是我不知道条件意味着什么。

<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>
javascript html json ajax
2个回答
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


0
投票

它指出:

  1. 将json对象作为来自'/ getGames'的响应并将结果保存在games变量中
  2. 迭代游戏并为每个游戏执行以下操作
  3. 检查当前游戏是否趋势(如果设置为true或1),如果是,它将在html树中找到id =“games”的元素,并在该元素下将附加声明后面的整个html结构
© www.soinside.com 2019 - 2024. All rights reserved.