开发者

Multiple Logical Operators in javascript

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 o开发者_StackOverflow中文版k, callMe()

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

What am I doing wrong?


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.


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 NaN or not. It doesn't check whether the parameter is actually number or not. So:

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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜