简体   繁体   English

检查变量是否(定义)在 JavaScript 中不起作用

[英]Check if variable is (defined) not working in JavaScript

Got confused by this behaviour.被这种行为弄糊涂了。 I thought doing something like:我想这样做:

if (variable name)
{
    ... do this...
}

should work.应该管用。 However if the variable is not defined, I just get 'ReferenceError: Can't find variable: "variable name, and the else block won't even be executed. For example the following snippet that I got off another StackOverflow question doesn't work when I test it. Any suggestions?但是,如果未定义变量,我只会得到“ReferenceError:找不到变量:”变量名,并且 else 块甚至不会被执行。例如,我从另一个 StackOverflow 问题中得到的以下代码片段没有当我测试它时工作。有什么建议吗?

if(persons_name) 
{
    var name = persons_name;
} 
else 
{
    var name = "John Doe";
}
if (typeof persons_name !== 'undefined') {
  ...
} else {
  ...
}

Note that you don't need braces with typeof .请注意,您不需要带有typeof的大括号。

Unlike a property, an unqualified name has to be defined before you can use it.与属性不同,必须先定义非限定名称,然后才能使用它。 So you if you were looking for a global variable persons_name you could write所以如果你正在寻找一个全局变量persons_name,你可以写

if (window.persons_name)

and it would evaluate to undefined if persons_name didn't exist.如果 person_name 不存在,它将评估为未定义。 Alternatively, you can simply declare persons_name if you expect it to exist.或者,如果您希望它存在,您可以简单地声明persons_name。

var persons_name;

This won't change the value of persons_name if it already exists.如果 person_name 已经存在,这不会改变它的值。

by saying var name;通过说var name; you define the variable;你定义变量; and by saying var name = "john doe";并通过说var name = "john doe"; you assign it a value.你给它一个值。

var name = (typeof persons_name !== 'undefined' || !(!!persons_name)) ?
    persons_name :
    'John Doe';

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

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