合并两个if语句以表示不同的变量

时间:2019-06-03 19:56:17

标签: javascript jquery html

我有两个用于两个不同目的的变量以产生一些信息,但是我想看看是否有更方便的方式写出来:

var One = 0;
var Team = 0;

if(items[i].NumberOfAttendees == '1' && items[i].ApplicationType == 'One')
{
    One += 1;
}
else if(items[i].NumberOfAttendees == '1' && items[i].ApplicationType == 'Team') 
{
    Team += 1;
}
else if(items[i].NumberOfAttendees == '2' && items[i].ApplicationType == 'One') 
{
    One += 2;
}
else if(items[i].NumberOfAttendees == '2' && items[i].ApplicationType == 'Team') 
{
    Team += 2;
}

etc...

是否有更方便的方法来调用此方法,同时又将OneTeam计数分开?

3 个答案:

答案 0 :(得分:0)

我认为项目是一个对象数组。

您可以简单地使用for循环遍历此数组

for (var i = 0; i < items.length; i++) {
}

在此循环中,获取 ApplicationType 的值,并使用开关块确定 Team One 时该怎么做。一旦确定,请检查 NumberOfAttendees 的值,如果该值大于0,则将其值添加到Team或One变量中。

var attendees;
var One = 0;
var Team = 0;
for (var i = 0; i < items.length; i++) {
  switch (items[i].ApplicationType) {
    case "Team":
      attendees = parseInt(items[i].NumberOfAttendees);
      if (attendees > 0) {
        Team += attendees;
      }
      break;

    case "One":
      attendees = parseInt(items[i].NumberOfAttendees);
      if (attendees > 0) {
        One += attendees;
      }
  }
}

答案 1 :(得分:0)

您可以尝试这样的方法,在您的for语句中,您可能会使用它来遍历items

var attendees = parseInt(items[i].NumberOfAttendees, 10);

if(isNaN(attendees)) {
    // No need to proceed, since parsing of attendees failed. 
    continue;
}

if(items[i].ApplicationType == 'One') {
    One += attendees;
}

if(items[i].ApplicationType == 'Team') {
    Team += attendees;
}

答案 2 :(得分:0)

尝试

if(items[i].ApplicationType == 'One') One+= +items[i].NumberOfAttendees;
if(items[i].ApplicationType == 'Team') Team+= +items[i].NumberOfAttendees;

var One = 0;
var Team = 0;

var items=[
  {ApplicationType:'One', NumberOfAttendees:'1'},
  {ApplicationType:'One', NumberOfAttendees:'1'},
  {ApplicationType:'One', NumberOfAttendees:'2'},
  {ApplicationType:'Team', NumberOfAttendees:'1'},
  {ApplicationType:'Team', NumberOfAttendees:'2'},
];

for(let i=0; i<items.length; i++) {
  if(items[i].ApplicationType == 'One') One+= +items[i].NumberOfAttendees;
  if(items[i].ApplicationType == 'Team') Team+= +items[i].NumberOfAttendees;
}

console.log({One, Team});