Home  >  Article  >  Web Front-end  >  Simple example of javascript simulation enumeration_javascript skills

Simple example of javascript simulation enumeration_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:56:421373browse

As follows, we define the Week enumeration:

Copy the code The code is 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 way. Take defining the DOM document node type as an example. The definition is as follows:

Copy the code The code is 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 The code is as follows:

alert(document.nodeType == Node.DOCUMENT_NODE); // -----> Output: true

Note that the above Node definition can be used as a correction for IE DOM node type constants are not supported (all other mainstream browsers support it).

Similar to C-like languages, the attribute values ​​corresponding to the enumerations in the above two examples are all integers. You may be thinking, can 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 implemented using JSON, and JSON can use any type of value! So, enumerations in JS can be any type of value. The following takes the String type as an example:

Copy code The code is 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

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

Copy code The code is 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:

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