请注意,doesNotExist
有意不存在,永远不会显示警报,而是在浏览器的控制台中留下错误。在 jQuery 回调中运行这段代码有什么特别之处,它会像这样失败?
HTML:
<div>Shown! But we failed before the alert. Check your console...</div>
CSS:
div { display: none; }
JS:
$('div').fadeIn(100, function() {
if (doesNotExist) {
alert('Nope');
}
else {
alert('Still nope');
}
});
最佳答案
在回调中运行该代码没有什么特别之处。无论它如何运行,它都会导致该异常。在表达式中使用未声明的变量名总是错误的(typeof
除外)。
检查一个变量是否被定义,你可以使用
if (typeof doesNotExist === "undefined") {
// it is undefined
}
现在只是告诉您它根本没有定义,或者它没有任何值(value);根据应用程序,两者都可能是合适的。如果它应该是全局的,那么:
if (!("doesNotExist" in window)) {
// not defined
}
检查 window
对象中的属性,这是全局变量所在的位置(好吧,全局 var
变量)。
关于javascript - 为什么在 jQuery 回调中检查变量是否存在会导致硬异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41046840/