Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use javascript to detect the existence of variables

Shulou Source: shulou.com Published: 2022-06-03 00:43:22 10月03日 Update

This article mainly explains "how to use javascript to detect the existence of variables", the content of the explanation is simple and clear, easy to learn and understand, the following please follow the editor's ideas slowly in depth, together to study and learn "how to use javascript to detect the existence of variables" bar!

In javascript, you can detect the existence of a variable by determining whether the value of the variable is "null" or whether the data type is "undefined". The syntax "if (typeof (a) = =" undefined "| | a = = null)".

The operating environment of this tutorial: windows7 system, javascript1.8.5 version, Dell G3 computer.

In the actual development process, there will be scenarios to determine whether a variable exists or not.

You only need to use 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 ("an is undefined")} else {console.log ("an is defiend")}

There will be errors, there may be blocking, and it is not elegant enough.

Solution:

/ / var axioms; if (typeof (a) = = "undefined" | | a = = null) alert ("an is undefined"); else alert ("an is defined")

Typeof is an operator for viewing data types and can be used in two ways:

Typeof (expression) typeof variable name

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'-- an undefined variable or value

'boolean'-- variable or value of Boolean type

'string'-- A variable or value of type string

'number'-- A variable or value of a numeric type

'object'-- A variable or value of the object type, or null (this is a historical legacy of js, which treats null as an object type)

'function'-- A variable or value of a function type

Use if (typeof (a) = = "undefined") to determine whether the variable an is undefined.

Thank you for your reading, the above is the content of "how to use javascript to detect the existence of variables". After the study of this article, I believe you have a deeper understanding of how to use javascript to detect the existence of variables, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Tags: Variables types detection operations data learning content characters strings expressions operators problems elegance not enough functions history can be passed scenarios actual objects Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Redmi Shulou Tech Info NVidia Microsoft Xiaomi