JavaScript If 语句条件不带运算符?它有什么作用?
我习惯 if 语句的条件为 ( x < y ) 或 ( x == y )。但在没有运算符的情况下,if 语句到底检查什么?即在下面的示例中 if (window.XMLHttpRequest)... 条件是什么?
谢谢。
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
I am used to if statements having a condition where ( x < y ) or ( x == y ). But in cases where there is no operator, what does the if statement check exactly? i.e. in the example below if (window.XMLHttpRequest)... what's the condition?
Thanks.
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
只要括号内的表达式返回除
false
、null
、0
、""
或 < code>undefined...if
语句中的块将被执行:-)事实上,以下所有内容都将起作用:
As long as the expression inside the parentheses returns something other than
false
,null
,0
,""
orundefined
... the block in theif
statement will be executed :-)In fact all of the following will work:
这是因为 JavaScript 引擎在测试条件时会将任何类型强制转换为布尔值。就好像你在做
It's because the JavaScript engine coerces any type into a boolean when testing a condition. It as if you were doing
这将检查
window
上是否存在名为XMLHttpRequest
的属性,其“truthiness”为 true。 Javascript 将各种值解释为 true:true、任何非 0 数值、任何非空对象引用或(我认为)任何非空字符串。在本例中,代码正在测试浏览器是否支持 XMLHttpRequest 属性,该属性是上述浏览器中向服务器发送异步请求的对象的构造函数。如果浏览器定义了此函数,则 if 语句的计算结果将为 true。
This checks whether there exists a property on
window
calledXMLHttpRequest
whose "truthiness" is true. Javascript interprets a variety of values as true: true, any non-0 numeric value, any non-null object reference, or (I think) any non-empty string.In this case, the code is testing whether the browser supports the XMLHttpRequest property, which is the constructor function for an object that sends asynchronous requests to the server in the above-mentioned browsers. If the browser defines this function, the if statement will evaluate to true.
在某些语言中,谓词确实必须返回布尔值。
在 JavaScript 中,情况并非如此。
有些情况如 0 或 false(可能还有其他)是 false,其余的都是 true
in some languages the predicate really has to return a boolean.
In javascript this isn't the case.
Some case like 0 or false (there might be others) are false, the rest is true