怎样用JS模拟实现枚举

前言

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

枚举主要特点

  • 枚举值不能重复
  • 不能被修改

实现

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)

以上就是怎样用JS模拟实现枚举的详细内容,更多关于JS的资料请关注脚本之家其它相关文章!

你可能感兴趣的:(怎样用JS模拟实现枚举)