2016-11-22 41 views
4

有沒有一種方法可以打印給定int值的枚舉字段的值?例如我有以下枚舉:Javascript - 從值中打印枚舉的名稱

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 

+0

所以你基本上要切換鍵和值在原始對象? – nicovank

+1

如果有兩個折射率相同的元素會怎樣? – Barmar

回答

7

您可以迭代鍵並測試該屬性的值。

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

1

https://jsfiddle.net/1qxp3cf8/

使用了...要經過對象道具erties並檢查它是否等於您正在查找的值。

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