我要编写一个应该遵循一组指令的函数,但这似乎不起作用。
这是说明
在其金额和BuyerCountry上使用.toLocaleString
函数,将金额格式设置为带有BuyerCountry货币符号的货币。国家及其货币符号位于您在入门代码中获得的国家(地区)数组中。如果买方国家/地区不在国家/地区,则
使用美国和该国家/地区并相应地设置货币格式。
我下面的代码似乎不符合我的要求,并不确定为什么
const countries = [
{
code: "US",
currency: "USD",
country: 'United States'
},
{
code: "NG”,
currency: "NGN”,
country: “Nigeria”
}
]
const formatAsMoney = (amount, buyerCountry) => {
let toCurrency = '';
countries.forEach(country => {
try {
if (value.country === buyerCountry) {
toCurrency = (amount).toLocalString(value.code, {
style: 'currency',
currency: value.currency
})
}
} catch (error) {
toCurrency = (amount).toLocalString(en-US, {
style: "currency",
currency: "USD"
});
}
});
return toCurrency;
}
请问可能是什么问题,我该如何解决?谢谢
答案 0 :(得分:0)
在迭代countries
数组时,
countries.forEach(country => {...})
您必须使用country
来获取country.code
country.currency
等值。
但是相反,您使用的是value.currency
value.code
,我认为是错字。
考虑到县阵列,
const countries = [{
code: "en-US",
currency: "USD",
country: "United States"
},
{
code: "en-NG",
currency: "NGN",
country: "Nigeria"
}
]
const formatAsMoney = (amount, buyerCountry) => {
let toCurrency = '';
let isFound = false;
countries.forEach(country => {
if(country.code === buyerCountry) { //I am not sure if you `country.name`, change the key accordingly
toCurrency = (amount).toLocaleString(country.code, {style: 'currency', currency: country.currency});
isFound = true;
}
});
if(!isFound){
toCurrency = (amount).toLocaleString('en-US', {style: "currency", currency: "USD"}); //here `en-US` should be a string
}
return toCurrency;
}
注意:您已经写了toLocalString
,应该是toLocaleString
,这里是一个错字。
答案 1 :(得分:0)
您有几个语法错误和一个逻辑问题。
'
,"
或反引号/ grave引起来。您不能使用”
toLocalString(en-US, {
,则en-US应该是字符串,例如'en-US'
。value
变量。您可能是说country
。Number.prototype.toLocalString()
方法,您可能是说toLocaleString()
。您迭代countries
数组,寻找匹配项,但是如果找不到匹配项,程序将返回一个空字符串,而不是 en-US 格式的货币。仅在出现错误时才使用默认格式。
我建议您使用find操作,而不要在没有提前退出条件的情况下进行迭代。
const countries = [{
code: "US",
currency: "USD",
country: 'United States'
}, {
code: "NG",
currency: "NGN",
country: "Nigeria"
}]
const formatAsMoney = (amount, buyerCountry) => {
let country = countries.find(({ country }) => country === buyerCountry) || {
code: 'US',
currency: 'USD'
}
return amount.toLocaleString(country.code, {
style: 'currency',
currency: country.currency
})
}
console.info(formatAsMoney(2.15, 'Nigeria'))
console.info(formatAsMoney(2.15, 'UK')) // won't be found