In processing HTML5 page value, found that when the error is not taken, JS program no longer execute, directly write a correction function processing
As follows:
| The code is as follows |
Copy Code |
Fixed undefined variable function checkunfined (value) { if (typeof (value) = = ' undefined ') { Return ""; } return value; }
|
It's a very common thing to judge whether it's undefined or not.
Look at the simple example below
| The code is as follows |
Copy Code |
if (typeof (VAL1) = = ' undefined ') { var VAL1 = "now defined"; }else { Alert ("already defined"); }
Alert ("val1=" + VAL1);
|
By judging typeof (VAL1) = = ' Undefin ' You can know whether a variable is defined or not. Incidentally, JavaScript does not have the concept of block, so although VAL1 is defined in the IF statement, it can still be accessed outside.
But note that if a VAR is defined within a function, then the variable is a local variable of that function.
Let's look at the following example
| The code is as follows |
Copy Code |
if (typeof (FUN1) = = ' undefined ') { Alert ("Now define the FUN1"); function FUN1 () { Alert ("This is FUN1"); } }else { Alert ("already defined"); }
|
What do you think the output should be?
The correct answer should be alert ("already defined");.
functions and variables, for the Funtion keyword, JavaScript is done during compilation, so the function is considered defined when executed.
This can be more specific to the definition of function
if (typeof (FUNC1) = = ' function ')
To check whether a function is declared. It may be useful for programs that make plug-ins.
Global object, you can use window. Variable name to judge:
| The code is as follows |
Copy Code |
if (window. MyObject = = null) { Window. MyObject = {}; } Or if (! () MyObject "in Window") { Window. MyObject = {}; } |
It is not recommended to use if (! MyObject) or if (!window. MyObject) way to determine whether an object exists, because when Myobject=false or myobject= "", this condition is also established.
Attached is an undefined method for determining the object:
| The code is as follows |
Copy Code |
var A; Alert (A = = undefined);//The first Alert (typeof a = = "undefined");/the second Alert (A = = = undefined);//similar to the first If you are determining whether a property of an object exists, you can use the following methods: var obj = {}; Alert (Obj.hasownproperty (' a ')); Alert (' A ' in obj); |