【问题标题】:Javascript - print the name of an enum from a valueJavascript - 从值中打印枚举的名称
【发布时间】:2017-04-06 18:37:21
【问题描述】:

有没有办法在给定 int 值的情况下打印枚举字段的值?例如我有以下枚举:

refractiveIndex = {"vacuum": 1, "air": 1.000293, "water": 1.33, "diamond": 2.419};

如果我有一个值,有没有办法打印枚举的名称。例如,假设我有一个变量设置为 1,我想打印出“真空”,我该怎么做:

var value = 1;
console.log(refractiveIndex(value)); // Should print "vacuum" to console

?

【问题讨论】:

  • 所以你基本上是想切换原始对象中的键和值?
  • 如果有两个折射率相同的元素怎么办?

标签: javascript enums


【解决方案1】:

您可以迭代键并针对属性值进行测试。

var refractiveIndex = {"vacuum": 1, "air": 1.000293, "water": 1.33, "diamond": 2.419},
    value = 1,
    key;

Object.keys(refractiveIndex).some(function (k) {
    if (refractiveIndex[k] === value) {
        key = k;
        return true;
    }
});
console.log(key);

ES6

var refractiveIndex = {"vacuum": 1, "air": 1.000293, "water": 1.33, "diamond": 2.419},
    value = 1,
    key = Object.keys(refractiveIndex).find(k => refractiveIndex[k] === value);

console.log(key);

【讨论】:

    【解决方案2】:

    https://jsfiddle.net/1qxp3cf8/

    使用 for...of 遍历对象属性并检查它是否等于您要查找的值。

    refractiveIndex = {
      "vacuum": 1,
      "air": 1.000293,
      "water": 1.33,
      "diamond": 2.419
    };
    
    var value = 1;
    for (prop in refractiveIndex) {
      if (refractiveIndex[prop] == value) {
        console.log(prop);
      }
    }
    

    如果你想要它作为一个函数,你可以这样写:

    function SearchRefractive(myValue) {
        for (prop in refractiveIndex) {
          if (refractiveIndex[prop] == myValue) {
            return prop;
          }
        }
    }
    var value = 1;
    SearchRefractive(value);
    

    【讨论】:

      猜你喜欢
      • 2021-04-17
      • 1970-01-01
      • 2012-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-02
      • 1970-01-01
      相关资源
      最近更新 更多