有没有办法可以在给定int值的情况下打印枚举字段的值?例如,我有以下枚举:
refractiveIndex = {"vacuum": 1, "air": 1.000293, "water": 1.33, "diamond": 2.419};
Run Code Online (Sandbox Code Playgroud)
如果我有一个值,有没有办法打印枚举的名称.例如,假设我将变量设置为1,我想打印出"vacuum",我该怎么做:
var value = 1;
console.log(refractiveIndex(value)); // Should print "vacuum" to console
Run Code Online (Sandbox Code Playgroud)
?
Nin*_*olz 13
您可以迭代密钥并测试属性的值.
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);Run Code Online (Sandbox Code Playgroud)
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);Run Code Online (Sandbox Code Playgroud)