怎样用JS模拟实现枚举

编程学习 2021-07-04 14:07www.dzhlxh.cn编程入门
这篇文章主要介绍了怎样用JS模拟实现枚举,对枚举感兴趣的同学,可以实验一下

前言

在当前的JavaScript中,并没有枚举这个概念,在某些场景中使用枚举更能保证数据的正确性,减少数据校验过程,狼蚁网站SEO优化就介绍一下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的资料请关注狼蚁SEO其它相关文章!

Copyright © 2016-2025 www.dzhlxh.cn 金源码 版权所有 Power by

网站模板下载|网络推广|微博营销|seo优化|视频营销|网络营销|微信营销|网站建设|织梦模板|小程序模板