有条件没有给出预期的答案

时间:2019-04-08 21:33:47

标签: javascript conditional

我正在写一个非常简单的条件,仅给出“其他”答案。

这个想法是,如果我的宠物(pets)比朋友(friendsPets)多,那么我需要将其分配给新变量(mostPets),以查看谁拥有最多的宠物。但是,当我记录新变量(mostPets)时,它只为我提供了条件的“其他”部分的答案。新变量在控制台中应记录为4,但仅记录为0。如果我重新排列条件语句,它的确为4-但我知道这是不对的。我知道这是一个相当简单的问题,但是我对此很陌生。有什么建议吗?

df.sum(axis = 1)

2 个答案:

答案 0 :(得分:1)

首先,您需要在执行条件之前声明变量mostPets,否则将无法在该条件之外访问变量。

此外,您的条件else-if书写不正确。经过这些更改,它应该可以像这样正常工作:

let pets = 2;
let friendsPets = 0;
pets = 4;

let mostPets;
if (pets > friendsPets) {
  mostPets = pets
} else if (friendsPets > pets) {
  mostPets = friendsPets
}
// Note in this scenario we are ignoring if the variables are the same value, it would be better to just put 'else' without an extra condition.
console.log(mostPets);

注意: 正如@mplungjan提到的,要缩短代码,您可以使用以下代码更改逻辑以得到相同的结果:

let mostPets = Math.max(pets, friendsPets);

答案 1 :(得分:1)

您错过了if,并且需要声明所有var,并且不要多次使用let。让内部大括号仅在所谓的范围内可见

您在注释中提到需要使用ifs,然后,如果要删除第二个条件,则不需要第二个条件:

const pets = 2;
const friendsPets = 0;
let mostPets = pets; // default - could be 0 or nothing (undefined)

if (pets > friendsPets) {
  mostPets = pets;
} else {
  mostPets = friendsPets;
}
console.log(mostPets);

// OR using the ternary operator;

mostPets = pets > friendsPets ? pets : friendsPets;
console.log(mostPets);

由于您正在比较数字,因此这是一个更优雅的版本

const pets = 2;
const friendsPets = 0;
let mostPets = Math.max(pets,friendsPets)

console.log(mostPets);