这是什么== - javascript运算符? [英] What is this ==- javascript operator?

查看:76
本文介绍了这是什么== - javascript运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我发现 == - == + 时,我一直在尝试不同的条件。 / p>

在JS控制台中,你可以写:

  var a = ; 

然后以下是真的

  a ==; 

但这是假的

  a ==; 

但是,如果你说:

  a ==  - ; 

  a == +; 

那么漂亮的 == - 运算符?

解决方案

它们不是不同的运算符。



写作:

  a ==  - ; 

被解析为:

 (a)==( - ); 

== + 也是如此。



由于Javascript的怪异类型转换规则,表达式的计算结果为 true 。发生以下情况:


  1. 一元 - (或 + )运算符将其操作数转换为数字。如果它是一个空白字符串,则此转换的结果为 0

  2. a ==( - 然后)等同于== 0 。如果与 == 比较的类型不同,则将其中一个(可能两者)转换为获得通用类型。在这种情况下,左侧的也会转换为 0

  3. 您最终将 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:

  1. the unary - (or +) operators converts its operand to a number. If it's a blank string, the result of this conversion is 0.
  2. 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 to 0 too.
  3. You end up comparing 0 to 0, which yields true.

(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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆