简体   繁体   English

如何使用 if [on hold] 检测数字是否大于 20 或大于 50

[英]How can I detect if a number is greater than 20 or greater than 50 with an if [on hold]

I try to detect when a number is greater than 10,20,30,40, etc. But this code does not work.我尝试检测一个数字何时大于 10、20、30、40 等。但这段代码不起作用。

var number = 35;
var text;
if(number >= 10){
text = "> 10"
}
else if(number >= 20){
text = "> 20"
}
else if(number >= 30){
text = "> 30"
}

It only takes me the first if它只需要我第一个 if

35 is ≥ 10. It is also ≥20 and ≥30, but you're checking for ≥10 first, so the statement within the first if is executed. 35 ≥ 10。它也是 ≥20 和 ≥30,但您首先检查 ≥10,因此执行第一个if中的语句。 Since the rest of the conditionals are else if rather than if , none of the others are tested.由于条件句的 rest 是else if而不是if ,因此没有测试其他条件句。

Ideally, check for ≥30 first.理想情况下,首先检查≥30。 Then ≥20.然后≥20。 Then ≥10.那么≥10。

var number = 35;
var text;

if(number >= 30){
    text = "> 30"
} else if(number >= 20) {
    text = "> 20"
} else if(number >= 10) {
    text = "> 10"
}

Reverse the order of the if 's.颠倒if的顺序。 The program will leave the if/else statement as soon as it encounters an if that is true, so you need to put the ones that will be false before the first that will be true.程序一旦遇到if为真,就会离开if/else语句,因此您需要将那些为假的语句放在第一个为真的语句之前。

if(number >= 30){
    text = "> 30"
}
else if(number >= 20){
    text = "> 20"
}
else if(number >= 10){
    text = "> 10"
}

This will give you the highest one it's greater than.这将为您提供大于它的最高值。

if you want to know all of the numbers it's greater than, you can do something like如果你想知道它大于的所有数字,你可以做类似的事情

text = "";

if(number >= 10){
    text += "> 10\n"
}
if(number >= 20){
    text += "> 20\n"
}
if(number >= 30){
    text += "> 30\n"
}

Since this isn't scalable (any number greater than 30 will just return 30), you can do something like this which will give you the multiple of 10 it's greater than由于这是不可扩展的(任何大于 30 的数字只会返回 30),你可以做这样的事情,它会给你 10 的倍数,它大于

text = "> " + (number/10) + "0";

You should do the same but in a different order, beginning from bigger to little, a sort will be a good idea if it were an array.你应该做同样的事情,但顺序不同,从大到小,如果它是一个数组,排序将是一个好主意。

var number = 35;
var text;
if(number >= 40){
text = ">= 40"
}
else if(number >= 30){
text = ">= 30"
}
else if(number >= 20){
text = ">= 20"
}
else if(number >= 10){
text = ">= 10"
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM