简体   繁体   English

如果语句起作用,为什么这个简单的JavaScript不起作用?

[英]Why doesn't this simple JavaScript if statement work?

This if statement doesn't work. 此if语句不起作用。 I would expect it to write "if" as the variable should be empty. 我希望它写“ if”,因为变量应该为空。 Or failing that I would expect "else" but there are neither 否则,我会期望“其他”,但两者都没有

You can also see it on JSFiddle in full not working glory 您也可以在JSFiddle上看到它完全无法正常工作

I think JSFiddle maybe having problems at the moment 我认为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();   
          }
}

In JavaScript, if you try to take the value of an undefined symbol, you get a ReferenceError . 在JavaScript中,如果尝试获取未定义符号的值,则会得到ReferenceError That's what's happening here. 这就是这里发生的事情。 variable is completely undefined, and so trying to take its value (so you can compare it with null ) is failing with a ReferenceError . variable是完全未定义的,因此尝试获取其值(以便可以将其与null进行比较)会失败,并出现ReferenceError You can see this in the Dev Tools of your browser: 您可以在浏览器的开发工具中看到以下内容:

在此处输入图片说明

This aborts the script code being run, since it's not caught. 这将中止正在运行的脚本代码,因为它没有被捕获。

If for some reason you need to check if a symbol is defined, there is a way to do that: The typeof operator, which you're already using: 如果出于某种原因需要检查是否定义了符号,则可以采用以下方法:您已经在使用typeof运算符:

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

If you apply typeof to a symbol you haven't defined, it doesn't throw an error; 如果将typeof应用于未定义的符号,则不会引发错误; instead, you get back the string "undefined" . 相反,您将获得字符串"undefined"


Note that typeof is an operator, not a function; 注意typeof是一个运算符,而不是一个函数; no need to wrap its operand in parentheses. 无需将其操作数包装在括号中。

variableundefined ,这与JSFiddle中显示的错误相同。

If I assume that you mistyped and that variable is supposed to be existingthread , then what you are doing wrong is that existingthread is neither undefined nor null , it is an empty string! 如果我假设您键入错误并且该variable应该是existingthread ,那么您做错了什么,那就是existingthread既不是undefined也不为null ,它是一个空字符串!

you could simplify your if clause by just saying if (existingthread) { ... } , if I am guessing correctly what you are trying to achieve. 您可以仅通过说if (existingthread) { ... }来简化if子句,如果我猜对了您要实现的目标。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM