简体   繁体   English

如何在Javascript中配置和查找枚举

[英]How to configure and lookup enums in Javascript

Using this technique to setup enums in javascript, I would now like to search based on some other variable in my function below. 使用这种技术在javascript中设置枚举,我现在想在下面的函数中基于其他变量进行搜索。

Here's the enum config: 这是枚举配置:

var enums_instrumentType = Object.freeze({
    CASH: 0,
    EQUITY: 1,
    COMPOSITE_INDEX:2 ,
    EXCHANGE_RATE:3 ,
    IR_INDEX: 4,
    IR_SWAP_INDEX: 5
});
var enums_tenorUnit = Object.freeze({
      DAY: 0,
      WEEK: 1,
      MONTH: 2,
      YEAR: 3
});

function test(){
   thisInstr = _.findWhere(instrumentsList, { id: mem.instrument_id });  // FIND IT !
   var tenor_unit = thisInstr.ir_index.tenor.unit;     // 0: DAY, 1: WEEK, etc.
   var tenor_size = thisInstr.ir_index.tenor.size;     // number of units

   // HOW TO LOOKUP tenor_unt IN enums_tenorUnit, where tenor_unit is an integer value ???

} }

thanks in advance... Bob 提前谢谢......鲍勃

assuming tenor_unit is something like 0 or 1 : 假设tenor_unit类似于01

var numericValue = _.keys(enums_tenorUnit)[tenor_unit];

however, if tenor_unit is something like DAY or WEEK then simply: 但是,如果tenor_unit类似DAYWEEK那么简单地说:

var numericValue = enums_tenorUnit[tenor_unit];

alternatively, if you're looking for a boolean result rather than the literal value and if tenor_unit is something like DAY or WEEK you could use the in operator : 或者,如果您正在寻找布尔结果而不是文字值,并且如果tenor_unit类似于DAYWEEK ,则可以使用in运算符

var tenorUnitExists = tenor_unit in enums_tenorUnit;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM