如果JavaScript中未定义变量,最合适的测试方法是什么?
我见过几种可能的方法:
if (window.myVariable)
Or
if (typeof(myVariable) != "undefined")
Or
if (myVariable) // This throws an error if undefined. Should this be in Try/Catch?
如果JavaScript中未定义变量,最合适的测试方法是什么?
我见过几种可能的方法:
if (window.myVariable)
Or
if (typeof(myVariable) != "undefined")
Or
if (myVariable) // This throws an error if undefined. Should this be in Try/Catch?
当前回答
您可以使用typeof,如下所示:
if (typeof something != "undefined") {
// ...
}
其他回答
if (typeof foo == 'undefined') {
// Do something
};
注意,在这种情况下不需要严格比较(!==),因为typeof将始终返回字符串。
// x has not been defined before
if (typeof x === 'undefined') { // Evaluates to true without errors.
// These statements execute.
}
if (x === undefined) { // Throws a ReferenceError
}
我个人使用
myVar === undefined
警告:请注意==用于==,并且myVar先前已声明(未定义)。
我不喜欢myVar==“undefined”的类型。我认为这是长篇大论,没有必要。(我可以用更少的代码完成同样的任务。)
现在有些人读到这篇文章时,会痛苦万分,尖叫道:“等等!WAAITT!!!undefined可以被重新定义!”
凉的我知道这一点。同样,Javascript中的大多数变量都可以重新定义。你应该永远不要使用任何可以重新定义的内置标识符吗?
如果你遵循这条规则,对你有好处:你不是伪君子。
问题是,为了在JS中做大量的实际工作,开发人员需要依赖于可重新定义的标识符。我没有听到有人告诉我我不应该使用setTimeout,因为有人可以
window.setTimeout = function () {
alert("Got you now!");
};
总之,不使用原始==undefined的“它可以被重新定义”参数是假的。
(如果您仍然害怕未定义被重新定义,为什么要盲目地将未经测试的库代码集成到代码库中?或者更简单:一个linting工具。)
此外,与typeof方法一样,该技术可以“检测”未声明的变量:
if (window.someVar === undefined) {
doSomething();
}
但这两种技术在抽象方面都存在漏洞。我劝你不要用这个甚至
if (typeof myVar !== "undefined") {
doSomething();
}
考虑:
var iAmUndefined;
要获取该变量是否已声明,可能需要使用in运算符。(在许多情况下,您可以简单地读取代码O_O)。
if ("myVar" in window) {
doSomething();
}
但是等等!还有更多!如果一些原型连锁魔法正在发生…?现在,即使是高级操作员也不够。(好吧,我已经完成了这一部分的工作,只是说99%的时间里,==未定义(和***咳嗽***类型)工作正常。如果你真的关心,你可以单独阅读这个主题。)
我知道检查undefined最可靠的方法是使用void 0。
这与较新和较旧的浏览器都兼容,并且不能像window那样被覆盖。在某些情况下,未定义的浏览器可以被覆盖。
if( myVar === void 0){
//yup it's undefined
}
在本文中,我了解到Undercore.js等框架使用此函数:
function isUndefined(obj){
return obj === void 0;
}