gpt4 book ai didi

javascript - 为什么这个简单的 JavaScript if 语句不起作用?

转载 作者:行者123 更新时间:2023-11-28 11:57:57 27 4
gpt4 key购买 nike

这个 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();
}
}

最佳答案

在 JavaScript 中,如果您尝试获取 undefined symbol 的值,则会收到 ReferenceError。这就是这里发生的事情。 variable 完全未定义,因此尝试获取其值(以便您可以将其与 null 进行比较)会失败,并出现 ReferenceError。您可以在浏览器的开发工具中看到这一点:

enter image description here

这会中止正在运行的脚本代码,因为它没有被捕获。

如果由于某种原因您需要检查符号是否已定义,有一种方法可以做到这一点:您已经在使用的 typeof 运算符:

if (typeof existingthread == 'undefined' || typeof variable == 'undefined') {

如果将 typeof 应用于尚 undefined symbol ,它不会抛出错误;相反,您会返回字符串“undefined”

<小时/>

请注意,typeof 是一个运算符,而不是一个函数;无需将其操作数括在括号中。

关于javascript - 为什么这个简单的 JavaScript if 语句不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19600151/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com