Enum flags in JavaScript

前端 未结 6 453
夕颜
夕颜 2021-01-30 08:23

I need to emulate enum type in Javascript and approach seems pretty straight forward:

var MyEnum = {Left = 1; Right = 2; Top = 4; Bottom = 8}

N

6条回答
  •  旧时难觅i
    2021-01-30 08:58

    You just have to use the bitwise operators:

    var myEnum = {
      left: 1,
      right: 2,
      top: 4,
      bottom: 8
    }
    
    var myConfig = myEnum.left | myEnum.right;
    
    if (myConfig & myEnum.right) {
      // right flag is set
    }
    

    More info:

    • Understanding bitwise operations in javascript
    • How to check my byte flag?

提交回复
热议问题