Make a variable meaningful:
1, the definition variable is variable declaration, similar to: Var str;
2, variable assignment is variable initialization, similar to str= "test";
These 2 steps can be one-step, that is, to define variables and assign values to variables, similar to: Var str= "Test";
A variable that has a defined but not assigned value retains a special value: undefined (not a string), or Var str; Str==undefined returns True
For an undefined variable, a variable that is not declared, only one operation can be performed, that is, the typeof operator is used to detect its data type (for example: typeof str or typeof (str), note: typeof is an operator, not a function, and the following parentheses are not necessary and can be omitted entirely. In addition typeof return is a string), perform other operations will be an error!
Clear the above concept, JS judge whether the variable has been assigned to the method is out:
Method 1:
| The code is as follows |
Copy Code |
var str; if (str==undefined) { Alert ("This variable has not been assigned a value") }else{ Alert ("This variable has been assigned a value.") } |
But the premise of this method is that the variable str must be defined, that is, the declaration of the variable, otherwise it will be an error, the cause of the error as shown in bold text!
Method 2:
| The code is as follows |
Copy Code |
if (typeof str = = ' undefined ') {//must be quoted, because TypeOf returns a string Alert ("This variable has not been assigned a value") }else{ Alert ("This variable has been assigned a value.") } Or it's going to be like writing function Check (Bianliang) { if (typeof (Bianliang) = = ' undefined ') { Alert ("Variable not defined oh"); }else{ Alert ("Variable defined oh"); } } |
Recommended use of Method 2, to JS to determine whether the variable has been assigned!!
In addition to the Var command, you can have another rewrite and get the correct result:
| The code is as follows |
Copy Code |
if (!window.myobj) { myobj = {}; } |
Window is the top-level object of JavaScript, and all global variables are its properties. Therefore, to determine whether the myobj is null equals to determine whether the Window object has a myobj attribute, so as to avoid referenceerror error because myobj is undefined. However, from the normative considerations of code, it is best to add Var to the second line:
| The code is as follows |
Copy Code |
if (!window.myobj) { var myobj = {}; } or write this: if (!window.myobj) { Window.myobj = {}; } |