我正在写一个非常简单的条件,它只给我“else”答案。
这个想法是,如果我比我的 friend (friendsPets)拥有更多的宠物(pets),那么我需要将其分配给一个新变量(mostPets)来查看谁拥有最多的宠物。但是当我记录新变量(mostPets)时,它只给出条件的“else”部分的答案。新变量应该在控制台中记录 4,但它只记录 0。如果我重新排列条件语句,它确实会给我 4 - 但我知道这是不对的。我知道这是一个相当简单的问题,但我对此还很陌生。有什么建议吗?
let pets = 2;
let friendsPets = 0;
pets = 4;
if (pets > friendsPets) {
let mostPets = pets
} else(friendsPets > pets)
let mostPets = friendsPets
console.log(mostPets);
最佳答案
首先,您需要在执行条件之前声明变量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);
关于javascript - 有条件不给出预期答案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55582081/