Enum flags in JavaScript

前端 未结 6 539
夕颜
夕颜 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条回答
  •  耶瑟儿~
    2021-01-30 09:09

    Flag Enumerations in JavaScript

    Flag enums: Values must increment by powers of 2

    var SEASONS = {
      Spring : 1,
      Summer : 2,
      Fall   : 4,
      Winter : 8
    };
    

    Cannot use 0 in a bitwise & operation to test for a flag b/c it will always result in zero. However, it can be used for logical comparisons.

    Usage examples (contrived)

    var getSeasonsSelected = function( seasons ) {
      var selected = [];
    
      // The perens are needed around the bitwise operation due to the
      // greater operator precedence of `===`
      if ( (seasons & SEASONS.Spring) === SEASONS.Spring ) selected.push('Spring');
      if ( (seasons & SEASONS.Summer) === SEASONS.Summer ) selected.push('Summer');
      if ( (seasons & SEASONS.Fall)   === SEASONS.Fall )   selected.push('Fall');
      if ( (seasons & SEASONS.Winter) === SEASONS.Winter ) selected.push('Winter');
    
      return selected;
    };
    
    var s1 = getSeasonsSelected( SEASONS.Spring | SEASONS.Fall );
    console.log(s1);
    //=> ["Spring", "Fall"]
    

提交回复
热议问题