[英]Interesting result while learning JavaScript. But I dont know why
I wrote the following code and got no output. 我编写了以下代码,但没有输出。 Here is the code
这是代码
var a1 = undefined;
var a2 = 5;
if(a1 > a2)
alert(1);
if(a1 < a2)
alert(2);
if(a1 >= a2)
alert(3);
if(a1 <= a2)
alert(4);
There was no alert box that came up which means that the if statements resulted in false. 没有出现警告框,这意味着if语句导致错误。 Can I know the reason?
我能知道原因吗?
JavaScript tries to casts the value of x
to number
using ToPrimitive (@RobG). JavaScript尝试使用ToPrimitive(@RobG)将
x
的值强制转换为number
。 Since x
is undefined, this will return NaN
which compares false to any value. 由于
x
是未定义的,因此将返回NaN
,该NaN
将false与任何值进行比较。 So it will always return false
. 因此它将始终返回
false
。
Where expressions using relational operators are involved, the Abstract Relational Comparison Algorithm is used to evaluate the operands, then the result is converted to true
or false
. 如果涉及使用关系运算符的表达式,则使用抽象关系比较算法来评估操作数,然后将结果转换为
true
或false
。
In the comparison algorithm, step 3a converts undefined
to NaN
. 在比较算法中,步骤3a将
undefined
转换为NaN
。 In step 3c it says that comparing NaN
to anything returns undefined . 在步骤3c中,它说将
NaN
与任何内容进行比较将返回undefined 。
In the steps for say the Less-than Operator , a result of undefined
is converted to false. 在说小于运算符的步骤中,
undefined
的结果转换为false。
So for the if statements in the OP, every test returns false
since they are all relational operators that all use the abstract relational comparison algorithm and one of the operands is undefined
. 因此,对于OP中的if语句,每个测试均返回
false
因为它们都是使用抽象关系比较算法的关系运算符,并且其中一个操作数undefined
。
As @jAndy mentioned in the comments,
You can't consider
. undefined
keyword as a value/Instance
正如@jAndy在评论中提到的那样,
您不能将
。 undefined
关键字视为value / Instance
undefined
is not a numeric type. undefined
不是数字类型。 Rather, it's a special value of the property undefined
of the Global Object
相反,它是
Global Object
undefined
的属性的特殊值
That's why the Expression if(undefined {operator} {operand value})
evaluates to false. 这就是为什么表达式
if(undefined {operator} {operand value})
得出false的原因。 But consider the code if(undefined == undefined)
returns true
但是考虑代码
if(undefined == undefined)
返回true
Hope this Clears the ambiguity! 希望这消除歧义!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.