Automatic enumeration value
suggest changeThis example assigns a value to each entry in an enum list so two entries do not accidentally share a value. Object.freeze dates from ECMAScript 5; see browser support.
const testEnum = function() {
// Initializes the enumerations
const enumList = [
"One",
"Two",
"Three"
];
const enumObj = {};
enumList.forEach((item, index) => enumObj[item] = index + 1);
// Do not allow the object to be changed
Object.freeze(enumObj);
return enumObj;
}();
console.log(testEnum.One); // 1 will be logged
const x = testEnum.Two;
switch(x) {
case testEnum.One:
console.log("111");
break;
case testEnum.Two:
console.log("222"); // 222 will be logged
break;
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents