nitroge / memories

日常学习累积的点点滴滴滴滴点点
7 stars 0 forks source link

如何创建一个枚举对象 #13

Open nitroge opened 3 years ago

nitroge commented 3 years ago

原文请戳这里!!

class Enum {
  constructor(...keys) {
    keys.forEach((key, i) => {
      this[key] = i;
    });
    Object.freeze(this);
  }

  *[Symbol.iterator]() {
    for (let key of Object.keys(this)) yield key;
  }
}

const daysEnum = new Enum(
  'monday',
  'tuesday',
  'wednesday',
  'thursday',
  'friday',
  'saturday',
  'sunday'
);

const days = [...daysEnum]; // Array of the enum values as strings