在javascript中有什么区别undefined == variable
和variable == undefined
都一样吗?如果我执行undefined === variable
或typeof variable == 'undefined'
,会有什么不同?
有人可以帮我吗
最佳答案
不要使用undefined
测试未定义的变量,而应使用typeof运算符!undefined
不是javascript关键字,它只是一个变量名。如果有人将var undefined = true
全局写入代码中的任何地方,则所有比较都会发生意外情况。
您应该考虑使用JSLINT或JSHINT之类的东西,以避免在JavaScript代码中出现此类错误。
除此之外,我总是会先编写比较参数,因为这就是我读取它的方式。
这就是为什么If the variable foo is undefined than
应该写为if (typeof foo === "undefined")
的原因
我不记得这种模式的名称,但是我很确定有一个:)