Home > Web Front-end > JS Tutorial > body text

How to define enum (enumeration type) in JavaScript? how to use?

不言
Release: 2019-01-07 16:00:50
Original
41566 people have browsed it

The enum type is also called an enumeration type. It is a type that can group multiple constants into one and append a series of values. The constants defined using enumerations are called enumerator lists. By default, the enumeration Lifters are numbered sequentially starting from zero. This article introduces you to the use of enumeration types in JavaScript.

How to define enum (enumeration type) in JavaScript? how to use?

What is enum (enumeration type) in JavaScript?

There is no enumeration type in JavaScript, except JavaScript All languages ​​have the enum keyword, but in order to use enumeration variables in JavaScript, we have to create it ourselves.

Let’s take a look at How to define enum (enumeration type) in JavaScript

Let’s take a look at a specific example of defining enum (enumeration type) in JavaScript

The code is as follows

var Fruit = {
    orange : 1,
    banana : 2,
    peach : 3,
    strawberry : 4
};
var myvar = Fruit.orange;
if (myvar == 1){
    console.log("It is an orange!");
}
else {
    console.log("It is NOT an orange");
}
Copy after login

The execution result is as follows

How to define enum (enumeration type) in JavaScript? how to use?

In the above code, we first create a A dictionary variable named Fruit.

Multiple enumerators are set in the Fruit variable and their integer values ​​are given respectively.

Then we use the operator to store the value of the orange enumerator in the variable myvar.

If the value of myvar is 1, display It is an orange! in the JavaScript console, otherwise display It is NOT an orange!.

Finally, in this case, myvar has a value of 1, so It is an orange! is displayed.

The above is the detailed content of How to define enum (enumeration type) in JavaScript? how to use?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!