大于或小于变量的切换大小写

我使用此代码输入数字,并使用小于和大于开关的情况下的数字进行比较以获取正确的结果,只有默认设置才有效


var sum=prompt("enter sum:");


// sum=50;

switch(sum)

{

case sum=0:

  alert("sucess");

  break;

case sum>50:

  alert("also sucess");

  break;

case sum<50:

  alert("failed");

default:

 alert("there is errorrrr");


}


杨魅力
浏览 200回答 3
3回答

largeQ

您可以使用switch (true):switch (true) {&nbsp; case sum === 0:&nbsp; &nbsp; alert('success');&nbsp; &nbsp; break;&nbsp; case sum < 50:&nbsp; &nbsp; alert('also success');&nbsp; &nbsp; break;&nbsp; case sum > 50:&nbsp; &nbsp; alert('failed');&nbsp; &nbsp; break;&nbsp; default:&nbsp; &nbsp; alert('there is an error.')&nbsp; &nbsp; break;}请注意,在您的代码中,第一种情况实际上是分配,并进行修改sum以将其设置为0。

肥皂起泡泡

如您所料,它实际上不起作用,将switch语句与所有情况进行比较,例如:switch (something){&nbsp; &nbsp; case 1: // something == 1 ?&nbsp; &nbsp; // ....}实际上,您所写的内容被解释为var sum = 42;switch(sum){&nbsp; &nbsp; case sum < 50: // sum == sum < 50 ? -> 42 == 42 < 50 ? -> 42 == true ? false !&nbsp; &nbsp; // ...相反,您可以使用switch true语句。//&nbsp; &nbsp; &nbsp; &nbsp; v-------&nbsp; &nbsp; &nbsp;convert the prompt to a numeric valuelet sum = + prompt("enter sum:");switch(true){//&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;VV----- notice the double equal&nbsp; case sum == 0:&nbsp; &nbsp; &nbsp; &nbsp;// true == sum == 0 ?&nbsp;&nbsp; &nbsp; alert("sucess");&nbsp; &nbsp; break;&nbsp; case sum > 50:&nbsp; &nbsp; alert("also sucess");&nbsp; &nbsp; break;&nbsp; case sum < 50:&nbsp; &nbsp; alert("failed");&nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp;//&nbsp; <---- You forgot a break; there&nbsp; default:&nbsp; &nbsp; alert("there is errorrrr");&nbsp; &nbsp; break;}

长风秋雁

你的想法很好sum=20;switch(true){case 50:&nbsp; alert("sucess");&nbsp; break;case (sum>50):&nbsp; alert("also sucess");&nbsp; break;case sum<50:&nbsp; alert("failed");&nbsp;break;&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;default:&nbsp;alert("there is errorrrr");}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript