As follows, we define the enumeration of week:
Copy Code code 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); -----> Output:1
Of course, we have a more intuitive approach. For example, define the DOM document node type as follows:
Copy Code code as follows:
if (typeof Node = = "undefined") {
var Node = {
Element_node:1,
Attribute_node:2,
Text_node:3,
Cdata_section_node:4,
Entity_reference_node:5,
Entity_node:6,
Processing_instruction_node:7,
Comment_node:8,
Document_node:9,
Document_type_node:10,
Document_fragement_node:11,
Notation_node:12
}
}
The test is as follows:
Copy Code code as follows:
Alert (Document.nodetype = = Node.document_node); -----> Output:true
Note that the above node definition can be used as a correction for IE does not support DOM node type constants (supported by other mainstream browsers).
Similar to the Class C language, the enumerated corresponding property values for the above 2 examples are all cosmetic. You might think, could it be defined as another type? To answer this question, we must first know the principle of our enumeration implementation. As mentioned earlier, this is achieved with JSON, and JSON can use any type of value! Therefore, the enumeration in JS can be any type of value. The following is an example of string type:
Copy Code code as follows:
if (typeof Color = = "undefined") {
var Color = {
Color1: ' Red ',
Color2: ' Green ',
Color3: ' White ',
Color4: ' Black '
}
}
The test is as follows:
alert (Color.color1); -----> output:red
Defining a personlist with a more complex type is enumerated as follows:
Copy Code code 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 shown below: