哪种检查变量是否已初始化的方法更好/正确?(假设变量可以保存任何内容(字符串、int、对象、函数等))
if (elem) { // or !elem
or
if (typeof elem !== 'undefined') {
or
if (elem != null) {
哪种检查变量是否已初始化的方法更好/正确?(假设变量可以保存任何内容(字符串、int、对象、函数等))
if (elem) { // or !elem
or
if (typeof elem !== 'undefined') {
or
if (elem != null) {
当前回答
我的首选是typeof(elem)!='未定义'&&elem!=无效的
无论您选择什么,请考虑将检查放入这样的函数中
function existy (x) {
return typeof (x) != 'undefined' && x != null;
}
如果您不知道变量已声明,请继续使用typeof(x)!='未定义'&&x!=无效的
如果您知道变量已声明但可能不存在,可以使用
existy(elem) && doSomething(elem);
您正在检查的变量有时可能是嵌套属性。您可以使用prop | |{}来检查问题属性的存在性:
var exists = ((((existy(myObj).prop1||{}).prop2||{}).prop3||{})[1]||{}).prop4;
在每个属性之后,使用(…“| |{}”).nexPro,以便丢失的属性不会引发错误。
或者,您可以使用existy,如existy(o)&&exist(o.p)&&existiny(o.p.q)&&doSomething(o.p.q)
其他回答
typeof运算符将检查变量是否真的未定义。
if (typeof variable === 'undefined') {
// variable is undefined
}
与其他运算符不同,typeof运算符在与未声明的变量一起使用时不会引发ReferenceError异常。
但是,请注意,typeof null将返回“object”。我们必须小心避免将变量初始化为null的错误。为了安全起见,我们可以使用以下方法:
if (typeof variable === 'undefined' || variable === null) {
// variable is undefined or null
}
有关使用严格比较==而不是简单相等==的更多信息,请参阅:JavaScript比较中应该使用哪个相等运算符(==vs==)?
我很惊讶这还没有被提及。。。
以下是使用此['var_name']的一些其他变体
使用此方法的好处是,它可以在定义变量之前使用。
if (this['elem']) {...}; // less safe than the res but works as long as you're note expecting a falsy value
if (this['elem'] !== undefined) {...}; // check if it's been declared
if (this['elem'] !== undefined && elem !== null) {...}; // check if it's not null, you can use just elem for the second part
// these will work even if you have an improper variable definition declared here
elem = null; // <-- no var here!! BAD!
这取决于情况。如果您正在检查代码之外可能或可能尚未全局定义的内容(例如jQuery),您需要:
if (typeof(jQuery) != "undefined")
(这里不需要严格相等,typeof总是返回字符串。)但是,如果函数的参数可能已传递,也可能未传递,则它们将始终被定义,但如果忽略,则为null。
function sayHello(name) {
if (name) return "Hello, " + name;
else return "Hello unknown person";
}
sayHello(); // => "Hello unknown person"
在问题中概述的特定情况下,
typeof window.console === "undefined"
与相同
window.console === undefined
我更喜欢后者,因为它更短。
请注意,我们只在全局范围内查找控制台(这是所有浏览器中的窗口对象)。在这种特殊情况下,这是可取的。我们不希望在其他地方定义控制台。
@BrianKelley在他出色的回答中解释了技术细节。我只是补充了不足的结论,并将其消化为更容易阅读的内容。
最高答案是正确的,请使用typeof。
然而,我想指出的是,在JavaScript中,undefined是可变的(出于某种不道德的原因)。所以只需检查varName!==undefined有可能不会总是像您期望的那样返回,因为其他库可能已经更改了undefineed。一些答案(比如@skalee's)似乎更倾向于不使用typeof,这可能会让人陷入麻烦。
处理此问题的“旧”方法是将undefined声明为一个var,以抵消任何潜在的undefined/override。然而,最好的方法仍然是使用typeof,因为它将忽略其他代码中对undefined的任何重写。特别是如果你正在编写代码,以供在野外使用,谁知道页面上还有什么其他内容。。。