这些条件有什么不同?
How are these conditionals any different?
为什么这两个条件不同:
不正确:
if (myObj !== null && typeof myObj !== "undefined")
因此,您必须先测试 typeof():
正确:
if (typeof myObj !== "undefined" && myObj !== null)
我从 w3schools 网站上删除了这个。根据 w3schools 的说法,您必须首先测试 typeof() ,为什么这会有所作为。条件看起来是一样的
如果变量未声明,第一个条件将抛出错误。
ReferenceError: myObj is not defined
请注意,&& 运算符是短路的,因此在第二种情况下,如果 myObj 未定义,则根本不会计算 myObj !== null
表达式。
有关详细信息,请参阅 here。
为什么这两个条件不同:
不正确:
if (myObj !== null && typeof myObj !== "undefined")
因此,您必须先测试 typeof():
正确:
if (typeof myObj !== "undefined" && myObj !== null)
我从 w3schools 网站上删除了这个。根据 w3schools 的说法,您必须首先测试 typeof() ,为什么这会有所作为。条件看起来是一样的
如果变量未声明,第一个条件将抛出错误。
ReferenceError: myObj is not defined
请注意,&& 运算符是短路的,因此在第二种情况下,如果 myObj 未定义,则根本不会计算 myObj !== null
表达式。
有关详细信息,请参阅 here。