Enums in Javascript with ES6

前端 未结 15 1849
青春惊慌失措
青春惊慌失措 2020-12-12 10:42

I\'m rebuilding an old Java project in Javascript, and realized that there\'s no good way to do enums in JS.

The best I can come up with is:

const C         


        
15条回答
  •  温柔的废话
    2020-12-12 11:28

    As mentioned above, you could also write a makeEnum() helper function:

    function makeEnum(arr){
        let obj = {};
        for (let val of arr){
            obj[val] = Symbol(val);
        }
        return Object.freeze(obj);
    }
    

    Use it like this:

    const Colors = makeEnum(["red","green","blue"]);
    let startColor = Colors.red; 
    console.log(startColor); // Symbol(red)
    
    if(startColor == Colors.red){
        console.log("Do red things");
    }else{
        console.log("Do non-red things");
    }
    

提交回复
热议问题