此if语句不起作用。我希望它写“if”,因为变量应该为空。或者失败,我会期待“其他”,但没有
你也可以在JSFiddle上看到完全没有工作的荣耀
我认为JSFiddle目前可能遇到问题
checkforthread();
function checkforthread() { // Check to see if it is a new or existing chat
// Set the variable
var existingthread = "";
document.write("test");
if (typeof(existingthread) == 'undefined' || variable == null) {
document.write("if");
gotostage3();
}
else {
document.write("else");
gotostage3();
}
}
答案 0 :(得分:3)
在JavaScript中,如果您尝试获取未定义符号的值,则会得到ReferenceError
。这就是这里发生的事情。 variable
完全未定义,因此尝试获取其值(因此您可以将其与null
进行比较)失败并显示ReferenceError
。您可以在浏览器的开发工具中看到这一点:
这会中止正在运行的脚本代码,因为它没有被捕获。
如果出于某种原因需要检查是否定义了符号,那么 就是这样做的方法:typeof
运算符,您已经在使用它:
if (typeof existingthread == 'undefined' || typeof variable == 'undefined') {
如果将typeof
应用于未定义的符号,则不会引发错误;相反,你得到了字符串"undefined"
。
请注意typeof
是一个运算符,而不是一个函数;无需将其操作数包装在括号中。
答案 1 :(得分:2)
variable
是undefined
,这与JSFiddle中显示的错误相同。
答案 2 :(得分:2)
如果我认为您输入错误并且variable
应该是existingthread
,那么您错误的是existingthread
既不是undefined
也不是{{1}它是一个空字符串!
如果我正确地猜测您要实现的目标,可以通过简单地说null
简化if
条款。