首先,countryMap
不是數組;它是一個對象,您正在使用的事實,JavaScript對象是關聯。陣列,但在JS我們保留術語「陣列」實際數字索引Array
秒。
對於實際的解決方案,你有幾種選擇。限制自己香草的Javascript,你可能要遍歷的元素countryMap
,將每個元素的.currencyCode
值與您正在查找的元素進行比較,並返回.currencySign
當你找到一個匹配時,來自同一個元素的值。像這樣的東西應該工作:
function signForCurrency(currencyCode) {
var country, data;
for (country in countryMap) {
// for...in can find things we don't actually care about,
// so make sure it's really a key in the map:
if (countryMap.hasOwnProperty(country)) {
data = countryMap[country];
if (data.currencyCode == currencyCode) {
return data.currencySign;
}
}
}
// if we get here, we didn't find a match, and the function
// will return the undefined value
}
這裏的工作fiddle。
隨着ECMAScript的2016的新Object#values方法,你將能夠使用鏈式表達式:
function signForCurrency(currencyCode) {
var data =
Object.values(countryMap).find(data => data.currencyCode == currencyCode)
return data ? data.currencySign : undefined;
}
代碼缺少後備return語句...如果貨幣代碼不匹配 – Arvind
倒不如檢查'hasOwnProperty'來避免額外原型的問題 –
@Arvind,因爲它會在這種情況下返回'undefined',這是一個合理的結果,不需要修改。 –