JS模拟实现枚举

一笑奈何 提交于 2020-03-15 21:00:18

前言

在当前的javascript中,并没有枚举这个概念,在某些场景中使用枚举更能保证数据的正确性,减少数据校验过程,下面就介绍一下javascript如何模拟实现枚举效果。

枚举主要特点

  1. 枚举值不能重复
  2. 不能被修改

实现

let days;
(function (days) {
    days[days["Sunday"] = 0] = "Sunday";
    days[days["Monday"] = 1] = "Monday";
    days[days["Tuesday"] = 2] = "Tuesday";
    days[days["Wednesday"] = 3] = "Wednesday";
    days[days["Thursday"] = 4] = "Thursday";
    days[days["Friday"] = 5] = "Friday";
    days[days["Saturday"] = 6] = "Saturday";
})(days || (days = {}));

这个时候days对象基本实现了枚举效果,可以通过枚举值或索引去访问days对象,但枚举有个重要特别是不能被修改,这个时候days是可以随意修改的;可以通过Object.freeze函数让对象不改修改,重新导出一个不可以修改的对象,完整代码如下:

let days;
(function (days) {
    days[days["Monday"] = 1] = "Monday";
    days[days["Tuesday"] = 2] = "Tuesday";
    days[days["Wednesday"] = 3] = "Wednesday";
    days[days["Thursday"] = 4] = "Thursday";
    days[days["Friday"] = 5] = "Friday";
    days[days["Saturday"] = 6] = "Saturday";
    days[days["Sunday"] = 0] = "Sunday";
})(days || (days = {}));

//导出可枚举对象
export EnumWeek = Object.freeze(days)
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!