[英]Multiple Logical Operators in javascript
I want to check the following 我要检查以下内容
1: Is xa number 1:是xa号
2. If x is less that 5 or greater than 15, sound alert 3. If all is ok, callMe() 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? 我究竟做错了什么?
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. 这样,如果x不是数字,则直接进入警报。 If it is a number, you go to the next check (is x < 5), and so on. 如果是数字,则转到下一个检查(x <5),依此类推。
All the other answers about the && vs || 关于&& vs ||的所有其他答案 are correct, I just wanted to add another thing: 是正确的,我只想添加另一件事:
The isNaN()
function only checks whether the parameter is the constant NaN
or not. isNaN()
函数仅检查参数是否为常数NaN
。 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. 为此,我建议首先根据您期望的值通过parseInt()
或parseFloat()
运行变量。 After that check for isNaN()
, because these functions return only numbers or NaN
. 在那之后检查isNaN()
,因为这些函数仅返回数字或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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.