JS模拟实现枚举

前言

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

 

枚举主要特点

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

资源搜索网站大全https://55wd.com 广州品牌设计公司http://www.maiqicn.com

实现

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)
posted @ 2020-09-28 14:50  浅笑·  阅读(668)  评论(0编辑  收藏  举报