Home >Web Front-end >JS Tutorial >How to detect whether a variable exists in javascript

How to detect whether a variable exists in javascript

青灯夜游
青灯夜游Original
2021-10-25 14:29:504053browse

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}".

How to detect whether a variable exists in javascript

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

How to detect whether a variable exists in javascript

Solution:

<script type="text/javascript">
 
//	var a=&#39;xixi&#39;; 
 
	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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn