为什么Javascript的OR返回的值不是true / false? [英] Why does Javascript's OR return a value other than true/false?

查看:76
本文介绍了为什么Javascript的OR返回的值不是true / false?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了获得浏览器视口宽度,我看到了这种结构:

I saw this construction in order to get the browser viewport width:

function () { return window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth; }

我理解所涉及的浏览器怪癖。我不明白的是为什么 || 返回值。所以我尝试了这个警报(未定义|| 0 || 3); ,果然,它提醒 3 。我发现这很奇怪,因为我希望 true false 。谁能解释一下发生了什么?

I understand the browser quirks involved. What I don't understand is why || returns the value. So I tried this alert(undefined || 0 || 3); and sure enough, it alerts 3. I find this bizarre, because I expect true or false. Could anyone explain what's going on?

推荐答案

看看ECMAScript标准部分 11.11二进制逻辑运算符

Take a look at the ECMAScript standards section 11.11 Binary Logical Operators


生产LogicalORExpression:
LogicalORExpression ||
LogicalANDExpression评估为
如下:

The production LogicalORExpression : LogicalORExpression || LogicalANDExpression is evaluated as follows:

1.评估LogicalORExpression。

1.Evaluate LogicalORExpression.

2 .Call GetValue(Result(1))。

2.Call GetValue(Result(1)).

3.Call ToBoolean(Result(2))。

3.Call ToBoolean(Result(2)).

4.如果结果(3)为真,则返回结果(2)。

4.If Result(3) is true, return Result(2).

5.评估LogicalANDExpression。

5.Evaluate LogicalANDExpression.

6.Call GetValue(结果(5))。

6.Call GetValue(Result(5)).

7.返回结果(6)。

7.Return Result(6).

因此它评估每个操作数的布尔转换,但返回操作数的实际

So it evaluates the boolean conversion of each operand, but returns the actual value of the operand.

如果您想知道Javascript如何将值转换为布尔值,请参阅 9.2 ToBoolean

If you want to know how Javascript converts values to a boolean, see section 9.2 ToBoolean

这篇关于为什么Javascript的OR返回的值不是true / false?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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