JavaScript迭代嵌套循环并返回特定值

时间:2018-11-15 20:56:20

标签: javascript arrays loops

我是Java语言的新手,正在尝试打印选定的NFL球队时间表。我已经创建了一个包含所有团队的下拉菜单。我希望用户能够选择他们的团队并查看他们的日程安排。我能够返回整个列表(每场比赛),但是我不知道如何只返回所选球队的比赛。这是我正在使用的数据。

"Schedule": [
    {
      "gameId": "1",
      "gameWeek": "1",
      "gameDate": "2018-09-06",
      "awayTeam": "ATL",
      "homeTeam": "PHI",
      "gameTimeET": "8:20 PM",
      "tvStation": "NBC",
      "winner": "PHI"
    },
    {
      "gameId": "2",
      "gameWeek": "1",
      "gameDate": "2018-09-09",
      "awayTeam": "BUF",
      "homeTeam": "BAL",
      "gameTimeET": "1:00 PM",
      "tvStation": "CBS",
      "winner": "BAL"

这是返回我所有游戏的代码。

function processData(data){

  schedule = data["Schedule"];

  for(eachGame in schedule){
    var game = schedule[eachGame];
    var week = game["gameWeek"];
    var homeTeam = game["homeTeam"];
    var awayTeam = game["awayTeam"];
    var winner = game["winner"];
    var tableRow = "<tr><td>" + week + "</td><td>" + homeTeam + "</td><td>" + awayTeam + "</td><td>" + winner + "</td></tr>";
    $("#output").append(tableRow);

  }
}

当awayTeam或homeTeam是用户选择的团队时,我需要返回。

谢谢!

3 个答案:

答案 0 :(得分:1)

为了将数组简化为只有很少的一项,我几乎总是建议使用Array.filter(),但是实际上我将首先针对您的情况提出一个替代解决方案。

如果您要使用filter来遍历所有项目并找到所需的项目,然后使用for遍历来将它们追加到表中,则需要遍历其中的一些相同的元素两次。

相反,我们可以通过执行以下操作来应用我们的逻辑来跳过我们不希望进入同一循环的游戏:

//If "team" is neither the away team, nor the home team, skip this game
if (![game.awayTeam, game.homeTeam].includes(team)) return; 

示例1:(添加了评论)

var data = { Schedule: [{ awayTeam: "Jets", homeTeam: "Bills", winner: "Bills", week: 1 }, { awayTeam: "Saints", homeTeam: "Cardinals", winner: "Cardinals", week: 1 }, { awayTeam: "Giants", homeTeam: "Bengals", winner: "Bengals", week: 2 }, { awayTeam: "Bills", homeTeam: "Jaguars", winner: "Bills", week: 2 }, { awayTeam: "Bills", homeTeam: "Patriots", winner: "Patriots", week: 3 } ] };

function setScheduleByTeam(team) {
  let schedule = data["Schedule"];    //Get the schedule
  var $outputTable = $("#output");    //Store the table as a variable
  $outputTable.find("tbody").empty(); //Empty out the current records

  schedule.forEach(function(game) {                             //For each game in the schedule
    if (![game.awayTeam, game.homeTeam].includes(team)) return; //Skip the record if our team isn't in it

    //Create + Append table row
    var tableRow = "<tr><td>" + game.week + "</td><td>" + game.homeTeam + "</td><td>" + game.awayTeam + "</td><td>" + game.winner + "</td></tr>";
    $outputTable.append(tableRow);
  });
}

//On button click
$("body").on("click", "button", function() {
  let team = $('#teamSelect').val();  //Get selected team
  setScheduleByTeam(team);            //Update the table to that team's schedule
});
td,th { padding: 5px 15px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="teamSelect">
  <option>Select Team</option>
  <option value="Bengals">Bengals</option>
  <option value="Bills">Bills</option>
  <option value="Jets">Jets</option>
</select>
<button>Go!</button>

<table id="output">
  <thead>
    <tr>
      <th>Week</th>
      <th>Home</th>
      <th>Away</th>
      <th>Winner</th>
    </tr>
  </thead>
</table>

但是,有些人可能会要求保持清洁,在这种情况下,我建议使用前面提到的filter方法:

示例2 (添加了评论)

var data = { Schedule: [{ awayTeam: "Jets", homeTeam: "Bills", winner: "Bills", week: 1 }, { awayTeam: "Saints", homeTeam: "Cardinals", winner: "Cardinals", week: 1 }, { awayTeam: "Giants", homeTeam: "Bengals", winner: "Bengals", week: 2 }, { awayTeam: "Bills", homeTeam: "Jaguars", winner: "Bills", week: 2 }, { awayTeam: "Bills", homeTeam: "Patriots", winner: "Patriots", week: 3 } ] };

//Filter out schedule to only games where awayTeam == team OR homeTeam == team.
//Returns the filtered team's schedule
const getGamesByTeam = (team) => data.Schedule.filter(g => g.awayTeam == team || g.homeTeam == team);

function updateScheduleTable(games) {  
  var $outputTable = $("#output");     //Store table as variable
  $outputTable.find("tbody").empty();  //Remove existing rows
  
  games.forEach(function(game) {  //For each game, append to table
    var tableRow = "<tr><td>" + game.week + "</td><td>" + game.homeTeam + "</td><td>" + game.awayTeam + "</td><td>" + game.winner + "</td></tr>";
    $outputTable.append(tableRow);
  });
  
}

$("body").on("click", "button", function() {
  let team = $('#teamSelect').val();  //Get the selected team
  let games = getGamesByTeam(team);   //Get a filtered array of one team's schedule
  updateScheduleTable(games);         //Update the table based on that set of games
});
td,th { padding: 5px 15px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="teamSelect">
  <option>Select Team</option>
  <option value="Bengals">Bengals</option>
  <option value="Bills">Bills</option>
  <option value="Jets">Jets</option>
</select>
<button>Go!</button>

<table id="output">
  <thead>
    <tr>
      <th>Week</th>
      <th>Home</th>
      <th>Away</th>
      <th>Winner</th>
    </tr>
  </thead>
</table>

答案 1 :(得分:0)

您需要根据用户选择的团队对数据数组进行排序。为此,您需要使用array method遍历数组并根据您放入循环中的逻辑返回值。为此,我使用了reduce方法(IMO是最有用的数组方法)。

function filterForSelectedTeam(data) {
  const accumulator = [];
  const team = $('#teamSelect').val();
  const schedule = data["Schedule"];
  // if team has a value this reduce method will return a sorted array
  // based on the logic in the loop.
  return team && schedule.reduce((acc, game) => {
    if (game["homeTeam"] === team || game['awayTeam'] === team) {
      acc.push(game);
    };
    return acc;
  }, accumulator);
}

const data = [] // your data here;
const gamesBySelectedTeam = filterForSelectedTeam(data)

gamesBySelectedTeam.forEach(game => {
  const tableRow = "<tr><td>" + game['gameWeek'] + "</td><td>" + game['homeTeam'] + "</td><td>" + game['awayTeam'] + "</td><td>" + game['winner'] + "</td></tr>";
  $("#output").append(tableRow);
});

答案 2 :(得分:0)

这里是一种只需几个方法调用即可完成此操作的方法:

function processData({ Schedule: s }, team) {
  // s is now the equivolent of data['Schedule']
  // Filter the data to get all games where either
  // the away of home team is the team sent in
  // Empty the table so it includes only those games appended below
  // Append the array of games as html elements
  $("#output")empty().append(
    s.filter(g => g.awayTeam === team || g.homeTeam === team)
    .map(g => {
      `<tr>
        <td>${game.gameWeek}</td>
        <td>${game.homeTeam}</td>
        <td>${game.awayTeam}</td>
        <td>${game.winner}</td>
      </tr>`
    })
  );
}

您可以将html字符串数组附加到DOM上,并且可以正确处理它们。