javascript javascript中的多个逻辑运算符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3967100/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 02:51:26  来源:igfitidea点击:

Multiple Logical Operators in javascript

javascript

提问by Naomi

I want to check the following

我想检查以下内容

1: Is x a number
2. If x is less that 5 or greater than 15, sound alert 3. If all is ok, callMe()

1:是 xa 数
2. 如果 x 小于 5 或​​大于 15,发出警报 3. 如果一切正常,则 callMe()

var x = 10;
if (isNaN(x) && ((x < 5) || (x > 15))) {
alert('not allowed')
}
else
{
callMe();
}

What am I doing wrong?

我究竟做错了什么?

回答by G?T?

var x = 10;
if (isNaN(x) || (x < 5) || (x > 15)) {
    alert('not allowed')
}
else
{
    callMe();
}

This way, if x is not a number you go directly to the alert. If it is a number, you go to the next check (is x < 5), and so on.

这样,如果 x 不是数字,您将直接转到警报。如果是数字,则转到下一个检查(是 x < 5),依此类推。

回答by Vilx-

All the other answers about the && vs || are correct, I just wanted to add another thing:

关于 && 与 || 的所有其他答案 是对的,我只是想补充一点:

The isNaN()function only checks whether the parameter is the constant NaNor not. It doesn't check whether the parameter is actually number or not. So:

isNaN()函数只检查参数是否为常量NaN。它不检查参数是否实际上是数字。所以:

isNaN(10) == false
isNaN('stackoverflow') == false
isNaN([1,2,3]) == false
isNaN({ 'prop' : 'value'}) == false
isNaN(NaN) == true

In other words, you cannot use it to check whether a given variable contains a number or not. To do that I'd suggest first running the variable through parseInt()or parseFloat()depending on what values you expect there. After that check for isNaN(), because these functions return only numbers or NaN. Also this will make sure that if you have a numeric string then it is also treated like a number.

换句话说,您不能使用它来检查给定的变量是否包含数字。为此,我建议首先通过parseInt()parseFloat()根据您期望的值运行变量。之后检查isNaN(),因为这些函数只返回数字或NaN。此外,这将确保如果您有一个数字字符串,那么它也被视为一个数字。

回答by spender

var x = 10;
if (isNaN(x) || (x < 5) || (x > 15)) {
    alert('not allowed')
}
else
{
    callMe();
}