2 回答

TA贡献1829条经验 获得超13个赞
首先,您需要在执行条件之前声明变量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);

TA贡献1845条经验 获得超8个赞
您错过了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);
添加回答
举报