Javascript emulates a simple instance of enumeration

  • 2020-03-30 02:15:03
  • OfStack

Let's define the enumeration of weeks as follows:


if(typeof WeekDay == "undefined"){ 
var WeekDay = {};
WeekDay.Sunday = 0;
WeekDay.Monday = 1;
WeekDay.Tuesday = 2;
WeekDay.Wedesay = 3;
WeekDay.Thursday = 4;
WeekDay.Friday = 5;
WeekDay.Saturday = 6;
}

The test is as follows:
Alert (WeekDay. Monday);   / / -- -- -- -- -- > The Output: 1.

Similar to class C language, the enumeration corresponding attribute values of the above two examples are all integers. You might think, what else can you define? To answer this question, we need to know how our enumeration works. As mentioned earlier, this is implemented using JSON, which can use any type of value! So, an enumeration in Js can be any type of value. Take the String type as an example:


if(typeof Color == "undefined"){ 
var Color = { 
Color1: 'red', 
Color2: 'green', 
Color3: 'white', 
Color4: 'black' 
} 
}

The test is as follows:
Alert (Color. Color1); / / -- -- -- -- -- > Output: red

Define a PersonList enumeration with a more complex type as follows:


if(typeof PersonList == "undefined"){ 
var PersonList = {
ZhangSan: {
Id: 1,
Name: 'ZhangSan',
Gender: 'man'
},
LiSi: {
Id: 2,
Name: 'LiSi',
Gender: 'woman'
},
ZhaoWu: {
Id: 3,
Name: 'ZhaoWu',
Gender: 'man'
}
}
}

The test results are as follows:

< img Alt = "" border = 0 SRC =" / / files.jb51.net/file_images/article/201403/20140306091237.png ">


Related articles: