[英]Do something if a variable is defined
In JS, I want to do something if a variable is defined or not. 在JS中,如果定义了变量,我想做一些事情。 I was under the impression this syntax would work: 我认为这种语法会起作用:
if (foo) {
console.log('foo is defined');
} else {
console.log('foo is not defined');
}
But I get a "Uncaught Reference Error: foo is not defined": 但我得到一个“未捕获的参考错误:未定义foo”:
http://jsfiddle.net/cfUss/ http://jsfiddle.net/cfUss/
Am I missing something? 我错过了什么吗? I thought this was very basic js and had used this syntax a ton before. 我认为这是非常基本的js,之前使用过这种语法。
There are two related concepts, being declared and being defined. 有两个相关的概念,即声明和定义。 Trying to reference a name which is not declared is what throws the error, not trying to reference a value which is undefined. 尝试引用未声明的名称会引发错误,而不是尝试引用未定义的值。
So for example: 例如:
var foo; //Declare the variable. It's still not defined however
if (foo) {
console.log('foo is defined');
} else {
console.log('foo is not defined');
}
Of course, if I actually want to detect something which is undeclared or undefined as you mention you want to do, I usually prefer to be more explicit and use if(typeof foo != "undefined")
since var foo; if (foo)
当然,如果我真的想要检测一些你想要提到的未声明或未定义的东西,我通常更喜欢更明确并使用if(typeof foo != "undefined")
因为var foo; if (foo)
var foo; if (foo)
doesn't trigger for defined but falsey values. var foo; if (foo)
不触发已定义但值为false的值。 Finally, you can do direct comparison to an undefined value if you want to test whether something is undefined and allow it to throw if undeclared, eg if(foo !== void(0))
最后,如果你想测试某些东西是否未定义并允许它在未声明的情况下抛出,你可以直接比较未定义的值,例如if(foo !== void(0))
if (typeof foo == "undefined") {
console.log('doesnt exist');
} else {
console.log('it exists');
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.