javascript - Javascript if 语句中的求值顺序

标签 javascript

为了保护我的代码不访问我使用的未声明的变量

if (typeof myVar != 'undefined')

这很好用,但我想在其中添加另一个 if 语句。像这样转换:

if (typeof myVar != 'undefined'){
    if (myVar == "test"){}
}

为此:

if (typeof myVar != 'undefined' && myVar == "test")

考虑到 myVar 可能未定义,这最后的代码在每种使用情况和每个浏览器 中是否安全?

是否有可能 if () 中的各种语句未按照它们编写的顺序求值?

如果 myVar 未定义,我可以假设 myVar == "test"永远执行吗?

最佳答案

Can I assume myVar == "test" will never be executed if myVar is undefined?

是的。您正在测试的表达式是 logical AND expression并且指定了两个操作数的求值顺序:

The production LogicalANDExpression : LogicalANDExpression && BitwiseORExpression is evaluated as follows (emphasis added):

  • Let lref be the result of evaluating LogicalANDExpression.
  • Let lval be GetValue(lref).
  • If ToBoolean(lval) is false, return lval.
  • Let rref be the result of evaluating BitwiseORExpression.
  • Return GetValue(rref).

这基本上是说计算第一个操作数,如果该计算的结果为 false,则整个表达式为 false,并且永远不会计算第二个操作数。

关于javascript - Javascript if 语句中的求值顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18507839/

相关文章:

javascript - 根据另一个单词数组对单词数组进行排序

javascript - 删除父级和其中的所有内容?

javascript - 如何切换按钮以将标题更改为不同的颜色并返回原始颜色

javascript - Jquery 旋转轨道与项目

javascript - AngularJS:指令重复,作为属性而不是元素

javascript - 如何删除javascript视差中页面末尾留下的额外空间

javascript - 如何通过数组合并进行映射,使每个结果都相同 [lodash]

javascript - 如何在angular2中单击按钮时触发表单验证

JavaScript : What is it about my code that means the second image only displays for a nano-second

javascript - 如何同时触发两个事件: onblur and onclick