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

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


这个想法是,如果我的宠物(pets)比朋友(friendsPets)多,那么我需要将其分配给新变量(mostPets),以查看谁拥有最多的宠物。但是,当我记录新变量(mostPets)时,它只为我提供了条件的“其他”部分的答案。新变量在控制台中应记录为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);


GCT1015
浏览 158回答 2
2回答

烙印99

首先,您需要在执行条件之前声明变量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);

精慕HU

您错过了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);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript