哪种检查变量是否已初始化的方法更好/正确?(假设变量可以保存任何内容(字符串、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) {
当前回答
这些答案(除了Fred Gandt解决方案)要么不正确,要么不完整。
假设我需要我的variableName;携带一个未定义的值,因此它是以var variableName等方式声明的;这意味着它已经初始化;-如何检查是否已申报?
或者更好——我如何立即检查“Book1.chapter22.paragraph37”是否存在一次调用,但不会引起引用错误?
我们通过使用最强大的JasvaScript运算符in运算符来实现
"[variable||property]" in [context||root]
>> true||false
其他回答
我很惊讶这还没有被提及。。。
以下是使用此['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!
if (typeof console != "undefined") {
...
}
或者更好
if ((typeof console == "object") && (typeof console.profile == "function")) {
console.profile(f.constructor);
}
适用于所有浏览器
我的首选是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)
这些答案(除了Fred Gandt解决方案)要么不正确,要么不完整。
假设我需要我的variableName;携带一个未定义的值,因此它是以var variableName等方式声明的;这意味着它已经初始化;-如何检查是否已申报?
或者更好——我如何立即检查“Book1.chapter22.paragraph37”是否存在一次调用,但不会引起引用错误?
我们通过使用最强大的JasvaScript运算符in运算符来实现
"[variable||property]" in [context||root]
>> true||false
最高答案是正确的,请使用typeof。
然而,我想指出的是,在JavaScript中,undefined是可变的(出于某种不道德的原因)。所以只需检查varName!==undefined有可能不会总是像您期望的那样返回,因为其他库可能已经更改了undefineed。一些答案(比如@skalee's)似乎更倾向于不使用typeof,这可能会让人陷入麻烦。
处理此问题的“旧”方法是将undefined声明为一个var,以抵消任何潜在的undefined/override。然而,最好的方法仍然是使用typeof,因为它将忽略其他代码中对undefined的任何重写。特别是如果你正在编写代码,以供在野外使用,谁知道页面上还有什么其他内容。。。