在下面的数组中,如何搜索currencyCode并输出currencySign?例如,如果我搜索“EUR”,则输出应为“”€“
<script>
var countryMap = {};
countryMap.AF = {
currencyCode: "AFN",
countryName: "Afghanistan",
currencySign: "؋"
};
countryMap.AX = {
currencyCode: "EUR",
countryName: "Åland Islands",
currencySign: "€"
};
</script>
答案 0 :(得分:3)
首先,countryMap
不是一个数组;它是一个对象。您正在使用Javascript对象是关联数组的事实,但在JS中我们保留术语&#34;数组&#34;对于实际的数字索引Array
s。
对于实际的解决方案,您有几种选择。将自己限制为vanilla Javascript,您可能需要遍历countryMap
的元素,将每个元素的.currencyCode
值与您要查找的元素进行比较,然后返回{{1}找到匹配项时来自同一元素的值。这样的事情应该有效:
.currencySign
这是一个有效的fiddle。
使用ECMAScript 2016的新Object#values方法,您将能够使用链式表达式:
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
}