一般咱们定义的枚举值:javascript
var SizeEnum = { SMALL: 1, MEDIUM: 2, LARGE: 3, };
使用var mySize = SizeEnum.SMALL;
java
若是须要包含其余属性,咱们能够添加额外的对象数组
var SizeEnum = { SMALL: 1, MEDIUM: 2, LARGE: 3, properties: { 1: {name: "small", value: 1, code: "S"}, 2: {name: "medium", value: 2, code: "M"}, 3: {name: "large", value: 3, code: "L"} } };
使用:this
var mySize = SizeEnum.MEDIUM; var myCode = SizeEnum.properties[mySize].code; // myCode == "M"
下面咱们进行封装:prototype
/** * 枚举类 * * @author harris.xc * @param props [{key: number|string, value: number|string, ...other}] * 栗子: * const StepEnum = new Enum([ * { key: 'STEP1', name: '步骤1', value: 1 }, * { key: 'SETP2', name: '步骤2', value: 2 }, * ]); * * @class Enum * * @method get(value) 经过value获取当前列的值 * return { key: 'SETP2', name: '步骤2', value: 2 } * * @returns {key1: number|string, key2: number|string} * { * CREATE: 1, * APPROVED: 2, * } */ export default class Enum { /** * 初始化 * @param {Array} props [] */ constructor(props = []) { this.__props = {}; if (props.length) { props.forEach((element) => { if (element.key && element.value) { this[element.key] = element.value; this.__props[element.value] = element; } else { console.error('Enum缺乏必要的key或value'); } }); } } /** * 根据value获取对象值 * @param {string|number} value 状态值 */ get(value) { return this.__props[value]; } /** * 获取枚举数组 */ getArray() { const arr = []; for (const key in this.__props) { if (Object.prototype.hasOwnProperty.call(this.__props, key)) { arr.push(this.__props[key]); } } return arr; } }
使用方法:code
let SizeEnum = new Enum([ { key: 'STEP1', name: '步骤1', value: 1 }, { key: 'SETP2', name: '步骤2', value: 2 } ]); SizeEnum.STEP1; // 1 SizeEnum.get(SizeEnum.STEP1); // { key: 'STEP1', name: '步骤1', value: 1 }