开发者

Check if variable is (defined) not working in JavaScript

开发者 https://www.devze.com 2023-03-28 19:54 出处:网络
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 v

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 snippe开发者_开发技巧t that I got off another StackOverflow question doesn't work when I test it. Any suggestions?

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.


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

if (window.persons_name)

and it would evaluate to undefined if persons_name didn't exist. Alternatively, you can simply declare persons_name if you expect it to exist.

var persons_name;

This won't change the value of persons_name if it already exists.


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


by saying var name; you define the variable; and by saying var name = "john doe"; you assign it a value.

0

精彩评论

暂无评论...
验证码 换一张
取 消