javascript - 有条件不给出预期答案

标签 javascript conditional-statements

我正在写一个非常简单的条件,它只给我“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/

相关文章:

javascript - Canvas 的旋转没有按照我的预期发生

c - 我正在尝试有条件地扫描数据,只要它不是 C 中文件的末尾

perl - 有条件地从菜单中排除菜单选项

java - android 条件语句中的 boolean 值?

Java 单个 IF 语句内的不同数量的条件

c++ - 如何在 C++ 中执行先前执行的代码行

javascript - React-自动建议和 ES5

javascript - Typescript 不知道 FormData 是什么

javascript - 从 gmail 线程中的 ZIP 文件中提取 CSV 并将数据写入 Google 表格

javascript - Bootstrap/AngularJs : How to set bold attribute for the active selection of nav class?