为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

GCT1015 2021-04-08 14:15:34
我正在写一个非常简单的条件,只给我“其他”答案。这个想法是,如果我的宠物(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 = friendsPetsconsole.log(mostPets);
查看完整描述

2 回答

?
烙印99

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);


查看完整回答
反对 回复 2021-04-22
?
精慕HU

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);


查看完整回答
反对 回复 2021-04-22
  • 2 回答
  • 0 关注
  • 157 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信