为了保护我的代码不访问我使用的未声明的变量
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 ifmyVar
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/