这是什么== - javascript运算符? [英] What is this ==- javascript operator?
问题描述
当我发现 == -
或 == +
时,我一直在尝试不同的条件。 / p>
在JS控制台中,你可以写:
var a = ;
然后以下是真的
a ==;
但这是假的
a ==;
但是,如果你说:
a == - ;
或
a == +;
那么漂亮的 == -
运算符?
它们不是不同的运算符。
写作:
a == - ;
被解析为:
(a)==( - );
== +
也是如此。
由于Javascript的怪异类型转换规则,表达式的计算结果为 true
。发生以下情况:
- 一元
-
(或+
)运算符将其操作数转换为数字。如果它是一个空白字符串,则此转换的结果为0
。 -
a ==( - 然后)
等同于== 0
。如果与==
比较的类型不同,则将其中一个(可能两者)转换为获得通用类型。在这种情况下,左侧的也会转换为
0
。 - 您最终将
0
与0
进行比较,产生true
。
(以上是Javascript如何得出这个结果的一个粗略示例,实际规则隐藏在 ECMAScript规范。您可以使用 ===
运算符来阻止转换并获取 false
如果比较对象的类型不同。)
I was stumbling around trying different conditions, when I discovered ==-
, or ==+
.
In a JS console, you can write:
var a = " ";
then the following is true
a == " ";
but this is false
a == " ";
However, it will be true if you say:
a ==- " ";
or
a ==+ " ";
So what is this nifty ==-
operator?
They're not distinct operators.
Writing:
a ==- " ";
gets parsed as:
(a) == (-" ");
The same goes for ==+
.
The expression evaluates to true
because of Javascript's weird type conversion rules. Something like the following occurs:
- the unary
-
(or+
) operators converts its operand to a number. If it's a blank string, the result of this conversion is0
. a == (-" ")
is then equivalent to" " == 0
. If types compared with==
are different, one (possibly both), get converted to get a common type. In this case, the" "
on the left-hand side gets converted to0
too.- You end up comparing
0
to0
, which yieldstrue
.
(The above is a rough example of how Javascript might come to this result, the actual rules are buried in the ECMAScript specification. You can use the ===
operator instead to prevent the conversions and get false
if the types of the compared objects are different.)
这篇关于这是什么== - javascript运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!