• 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)
  • 相关阅读:
    Spring整合CXF之添加拦截器
    Spring整合CXF之发布WebService服务
    CXF添加自定义拦截器
    cxf处理一些Map等复杂类型
    webservice执行过程深入理解
    谈谈房车
    关于贷款消费
    记一次玩比特币的经历
    那年K城暑期工
    SpringBoot整合Xxl-Job
  • 原文地址:https://www.cnblogs.com/qianxiaox/p/13744683.html
Copyright © 2020-2023  润新知