In JavaScript, you can detect whether a variable exists by judging whether the value of the variable is "null" or whether the data type is "undefined". The syntax is "if(typeof(a)=="undefined"||a ==null){//Does not exist}else{//Exists}".
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
In the actual development process, there will be scenarios to determine whether a variable exists.
You only need to use it to determine whether the value of the variable is null or whether the data type is undefined; if so, it does not exist.
The first thing that comes to mind is
if(a==undefined){ console.log("a is undefined") }else{ console.log("a is defiend") }
An error will be reported here, it may cause blocking, and it is not elegant enough
Solution:
<script type="text/javascript"> // var a='xixi'; if(typeof(a) == "undefined" || a == null) alert("a is undefined"); else alert("a is defined"); </script>
typeof is an operator used to view data types. There are two ways to use it:
typeof(表达式) typeof 变量名
The first is to operate on expressions, and the second is to operate on variables.
The return type of the typeof operator is a string, and the values include the following:
'undefined' --Undefined variable or value
'boolean' --A variable or value of Boolean type
'string' --A variable or value of string type
'number' -- a variable or value of numeric type
'object' -- a variable or value of object type, or null (this is a legacy issue from js history, will null is treated as object type)
'function' -- a variable or value of function type
Use if (typeof(a )=="undefined")
can determine whether variable a is undefined.
[Recommended learning: javascript advanced tutorial]
The above is the detailed content of How to detect whether a variable exists in javascript. For more information, please follow other related articles on the PHP Chinese website!