在下面的数组中,如何搜索 currencyCode 并输出 currencySign?例如,如果我搜索“EUR”,输出应该是“”€”
<script>
var countryMap = {};
countryMap.AF = {
currencyCode: "AFN",
countryName: "Afghanistan",
currencySign: "؋"
};
countryMap.AX = {
currencyCode: "EUR",
countryName: "Åland Islands",
currencySign: "€"
};
</script>
最佳答案
首先,countryMap
不是一个数组;它是一个对象。您使用的事实是 Javascript 对象是关联 数组,但在 JS 中,我们为实际的数字索引 Array
保留术语“数组”。
对于实际的解决方案,您有多种选择。限制我们使用 vanilla 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;
}
关于javascript - 在 Javascript 数组中搜索字符串匹配并输出内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34713801/