此条件声明意味着什么?

时间:2019-02-10 12:15:40

标签: javascript html json ajax

我正在建立一个游戏评论网站,我的朋友帮助我提出了一个条件声明,确定游戏是否趋向流行,然后显示是否流行。事情是我不知道情况意味着什么。

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

2 个答案:

答案 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)

它指出:

  1. 从“ / getGames”获取json对象作为响应并将结果保存在游戏变量中
  2. 遍历游戏,并为每个游戏执行以下操作
  3. 检查当前游戏是否趋向趋势(如果设置为true或1),如果是,它将在html树中找到id =“ games”的元素,并在该元素下追加以下的整个html结构。声明