使用if / else确定获胜者

时间:2018-04-30 05:35:32

标签: javascript console operators

任何人都可以帮助我并向我解释如何在if / else语句中使用运算符,我正在尝试做一些简单的事情并得到两个不同乘法的结果,我是一个自学成才的开发人员所以请承担和我一起

var oscar = {
  height: 155,
  age: 22,
};
var andrew = {
  height: 170,
  age: 16,
};

if ((oscar * 5) > (andrew * 5)) {
  console.log('Oscar is the winner');
} else if ((oscar * 5) < (andrew * 5)) {
  console.log('Andrew is the winner')
} else {
  console.log('No winner')
}

2 个答案:

答案 0 :(得分:2)

变量是对象,必须指定比较属性。 无需乘以5。

&#13;
&#13;
var oscar = {
  height: 155,
  age: 22
};
var andrew = {
  height: 170,
  age: 16
};

if ((oscar.height) > (andrew.height)) {
  console.log('Oscar is the winner');
} else if ((oscar.height) < (andrew.height)) {
  console.log('Andrew is the winner')
} else {
  console.log('No winner')
}
&#13;
&#13;
&#13;

答案 1 :(得分:0)

你无法比较那样的对象。

也许你想分配一些分数?然后添加另一个可以在

上计算的属性

如果将等号的两边乘以相同的数字

,也不需要乘以任何东西

你可以这样做:

&#13;
&#13;
function scoreIt(p1,p2) {

  var diff = p1.points - p2.points;
  console.log("diff", diff);

  if (diff > 0) {
    console.log(p1.name+ ' is the winner with ' + p1.points);
  } else if (diff < 0) {
    console.log(p2.name + ' is the winner with ' + p2.points);
  } else {
    console.log('No winner - tied score ' + p1.points);
  }
}

var participant1 = {
  name: "Oscar",
  height: 155,
  age: 22,
  points: 8 // no trailing comma
};
var participant2 = {
  name: "Andrew",
  height: 170,
  age: 16 // no trailing comma
};

// later somewhere:
participant2.points = 9; // assignment
scoreIt(participant1,participant2);

participant1.points += 5; // increase
scoreIt(participant1,participant2);

participant2.points += 4;
scoreIt(participant1,participant2);
&#13;
&#13;
&#13;

如果使用名称作为键,对象会更好:

var participants = {
  "Oscar": {
    height: 155,
    age: 22,
    points: 8 // no trailing comma
  },
  "Andrew" : {
    height: 170,
    age: 16 // no trailing comma
  }
}