最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript - print the name of an enum from a value - Stack Overflow

programmeradmin1浏览0评论

Is there a way I can print the values of the enum field given the int value? for example I have the following enum:

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

If I have a value, is there a way to print the name of the enum. For example lets say I have a variable set to 1 and I want to print out "vacuum", how do I do that:

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

?

Is there a way I can print the values of the enum field given the int value? for example I have the following enum:

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

If I have a value, is there a way to print the name of the enum. For example lets say I have a variable set to 1 and I want to print out "vacuum", how do I do that:

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

?

Share Improve this question asked Nov 22, 2016 at 22:29 user2417339user2417339 2
  • So you basically want to switch the keys and the values in your original object? – user2345 Commented Nov 22, 2016 at 22:32
  • 1 What if there are two elements with the same refractive index? – Barmar Commented Nov 22, 2016 at 22:41
Add a comment  | 

2 Answers 2

Reset to default 13

You could iterate the keys and test against the value of the property.

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);

https://jsfiddle.net/1qxp3cf8/

use for...of to go through the object properties and check if it equals the value you're looking for.

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);
  }
}

if you wanted it as a function you could write it as this:

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

评论列表(0)

  1. 暂无评论