Home>
Contents of question

I want to define an integer type enumerator so that it can be used as an array subscript in Javascript. How should I write it?
Typescript seems to have an enum syntax, but Javascript doesn't have an enum syntax.

I want to define an enumerator that doesn't need to be cast and is recognized as an integer type, like the C ++ enumerator below.
I look forward to working with you.

What i am looking for

  • Constant (will not change later)
  • Represents an integer value and can be used as an array subscript
  • -1 Consecutive integers starting with (-1, 0, 1, 2, ...)
  • I want to define a constant under a certain namespace (in C ++, define it in a certain namespace and refer to the constant as Number :: Zero instead of Zero)
#include<iostream>
#include<vector>
struct Number
{
    enum type
    {
        Null = -1, // Constant representing -1
        Zero, // A constant representing 0
        One, // Constant representing 1
        Two, // A constant representing 2
    };
};
int main ()
{
    std :: vector<std :: string>array = {"a", "b", "c"};
    // Enumerator recognized as an integer type
    std :: cout<</pre>
<strong>What I tried</strong>
<p>After investigating, a sample using Symbol came out, but it seems that it can not be used as a subscript probably because it is not recognized as an integer type.</p>
<pre><code data-language = "JavaScript">const Number = Object.freeze ({{
  Zero: Symbol (0),
  One: Symbol (1),
  Two: Symbol (2)
});
let array = ["a", "b", "c"];
console.log (array [Number.Two]);// undefined

I thought about defining each variable as a variable, but since it is defined in the global namespace and there are about 50 constants, it becomes complicated, so please tell me if there is a simpler method.

const Zero = 0;
const One = 1;
const Two = 2;
environment
  • ES 2019
  • Answer # 1

    Is it something like this?

    const number = Object.freeze ({{
      Zero: 0,
      One: 1,
      Two: 2
    });

    I want to define an integer type enumerator so that it can be used as an array subscript in Javascript. How should I write it?

    In ECMAScript 2019, only String type/Symbol type can be specified for the property name of the object.
    MapIf you use, you can handle Number type.

    const map = new Map ([[-1,'Null'], [0,'Zero'], [1,'One'], [2,'Two']]);

    Re: tiitoi

  • Answer # 2

    The definition of the Enum class.
    (JavaScript abstraction can only be done by class or original prototype)

    const EnumCaseStruct = (() =>{
      const key = Symbol ();
      return class EnumCaseStruct {
        constructor (val) {
          this [key] = val;
        }
        // Refer to Swift and make it possible to get the value with rawValue
        get rawValue () {
          return this [key];
        }
      };
    }) ();
    class Enum {
      constructor (... cases) {
        if (! cases.every (v =>{
          switch (typeof v) {
            case'object':
              // For objects, each key value is defined as an instance of the above class
              Object.keys (v) .forEach (ve =>{
                Object.defineProperty (this, ve, {value: new EnumCaseStruct (v [ve])});
              });
              return true;
            case'string':
              // If it is a string type, initialize it as it is
              Object.defineProperty (this, v, {value: new EnumCaseStruct (v)});
              return true;
              defalult:
                // Only accept objects or strings
                return false;
          }
        })) {
          // Throw an error except for objects or strings
          throw new Error ('Type error!');
        }
      }
    }

    How to use.

    const fruits = new Enum (
      {apple: 25},
      {melon: 125}
    );
    const apple01 = fruits.apple;
    const apple02 = fruits.apple;
    console.log (apple01 == apple02);// true
    // Because it is a variable length argument, it can also be defined as follows
    const fruits02 = new Enum (
      {
        apple: 25,
        melon: 125
      },
      'pine'
    );
    // Each enum is false when compared because each value is unique.
    console.log (fruits.apple == fruits02.apple);// false
    // Refer to Swift and return the set value in rawValue
    console.log (fruits.apple.rawValue);// 25
    // If you enter the string as it is, rawValue returns that string
    console.log (fruits.pine.rawValue);// pine

    Because it is a pseudo
    It may not meet the requirements,
    I think it's a lot closer to the usability of enumerations.