什么是Javascripts的语义如果声明 [英] What Are the Semantics of Javascripts If Statement

查看:92
本文介绍了什么是Javascripts的语义如果声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直认为if语句基本上比较了它的类似于 == true 的参数。然而,Firebug中的以下实验证实了我最糟糕的恐惧 - 在写了15年的Javascript后我仍然没有任何线索WTF正在进行中:

I always thought that an if statement essentially compared it's argument similar to == true. However the following experiment in Firebug confirmed my worst fears—after writing Javascript for 15 years I still have no clue WTF is going on:

>>> " " == true
false
>>> if(" ") console.log("wtf")
wtf

我的世界观是在这里乱糟糟的。我可以运行一些实验来了解更多信息,但即使这样,我也会因为害怕浏览器怪癖而失眠。这是某个规格吗?它是否一致的跨浏览器?我会掌握javascript吗?

My worldview is in shambles here. I could run some experiments to learn more, but even then I would be losing sleep for fear of browser quirks. Is this in a spec somewhere? Is it consistent cross-browser? Will I ever master javascript?

推荐答案

如果两个操作数不是同一类型,JavaScript会转换操作数然后应用严格如果操作数是数字或布尔值,则操作数将转换为数字;如果任一操作数是字符串,则另一个操作数转换为字符串。

"If the two operands are not of the same type, JavaScript converts the operands then applies strict comparison. If either operand is a number or a boolean, the operands are converted to numbers; if either operand is a string, the other one is converted to a string."

https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators / Comparison_Operators

所以第一个做:

Number(" ")==Number(true)

虽然第二个评估如下:

While the second one is evaluated like this:

if(Boolean(" ")==true) console.log("wtf")

这篇关于什么是Javascripts的语义如果声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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