我有一个困扰我的问题。如果声明a var a
,然后尝试使用“ in”运算符对其进行测试,则得到的结果为真,例如,如果我使用点符号进行相同的测试,则得到的结果为假。
var a;
if('a' in window) {
console.log('a in window'); // this is written to the console
}
if (window.a) {
console.log('window.a'); // nothing happening here
}
现在我注意到,当我给aa这样的值时,两个输出都可以工作...看一下并注意到我如何检查它是否不存在:
var a;
if('a' in window) {
console.log('a in window'); // this is written to the console
}
if (!window.a) {
console.log('!window.a'); // this is written to the console
}
a = 1;
if (window.a) {
console.log('window.a'); // this is written to the console
}
那么,为什么仅在为变量分配值时才使用点符号?我知道一个愚蠢的问题,但到目前为止,我还不能得到确切的答案!
正如Johan所指出的那样,该支票正获得虚假价值。
if ('a' in window) console.log("a exists");
if (window.a) console.log("window.a is a truthy value");
if (!window.a) console.log("window.a is a falsey value");
if (typeof window.a != "undefined") console.log("window.a is not undefined");
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句