Automatic enumeration value

suggest change

This 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;
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents