我在switch语句之外声明变量contactNumber
,然后尝试在switch语句中分配它。但是,当它到达赋值时,我在switch语句中执行的赋值行上得到一个错误SyntaxError: Unexpected identifier
function helplineContactMessageForCountryCode(countryCode) {
var contactNumber = ''
switch (countryCode) {
case 'NG':
contactNumber = '234-01-772-2200'
break
case 'UG':
contactNumber = '0800-100-330'
break
case 'US'
contactNumber = '1-800-232-4636'
break
case 'ZA':
contactNumber = '0800-012-322'
break
default:
//Return empty string if no country code is found
return ''
}
return 'You can try calling the Toll-Free HIV and AIDS Helpline and speak to a human - ' + contactNumber
}
答案 0 :(得分:0)
如果' US'您缺少:。添加后,它应该像参加者一样工作。
我还建议使用对象映射而不是switch语句为您提供精确的用例,以使代码缩短和更好
function helplineContactMessageForCountryCode(countryCode) {
const codeMap = {
NG: '234-01-772-2200',
UG: '0800-100-330',
US: '1-800-232-4636',
ZA: '1-800-232-4636'
};
var number = codeMap[countryCode];
if (number) {
return 'You can try calling the Toll-Free HIV and AIDS Helpline and speak to a human - ' + number;
}
return '';
}
示例中的代码在helplineContactMessageForCountryCode中设置,但理想情况下应该在其他地方声明它。
答案 1 :(得分:0)
您在“美国”:
之后错过了case
。
function helplineContactMessageForCountryCode(countryCode) {
var contactNumber = ''
switch (countryCode) {
case 'NG':
contactNumber = '234-01-772-2200';
break;
case 'UG':
contactNumber = '0800-100-330';
break;
case 'US':
contactNumber = '1-800-232-4636';
break;
case 'ZA':
contactNumber = '0800-012-322';
break;
default:
contactNumber = contactNumber;
break;
}
return 'You can try calling the Toll-Free HIV and AIDS Helpline and speak to a human - ' + contactNumber
}