[我认为使用switch语句是太多代码,我在某些网站上看到了更好的方法来简化switch语句,甚至转换为对象文字,如在此网站上显示的一些示例,在下面链接]]
Rewriting Javascript: Replacing the Switch Statement
Using object literals and map method instead of the old switch statement
我试图转换switch语句,这是使用的示例。两者均无法正常工作,选择国家时显示的城市列表错误。英格兰正在显示scotland-cities.html等。
Ex:1
const city = (county) => ({ "England": $('#uk_states').load('england-cities.html'), "Scotland": $('#uk_states').load('scotland-cities.html'), //... })[county] let county = city([$('#Uk_Cities option:selected').text()]);
Ex:2
let city = { "England": { "file": $('#uk_states').load('england-cities.html'), "label": "england" }, "Scotland": { "file": $('#uk_states').load('scotland-cities.html'), "label": "scotland" }, //... let county = city[$('#Uk_Cities option:selected').text()]; let countryCity = `${county.file} ${county.label}`;
我认为此问题可能来自
let county = city([$('#Uk_Cities option:selected').text()]);
我不知道在转换为对象文字和城市类型词典时是否正确放置了开关(县)。>>
你们能帮我吗?
非常感谢。
let county = $('#Uk_Cities option:selected').text();
switch (county) {
case 'England':
$('#uk_states').load('england-cities.html');
break;
case 'Scotland':
$('#uk_states').load('scotland-cities.html');
break;
case 'Wales':
$('#uk_states').load('wales-cities.html');
break;
case 'Northern Ireland':
$('#uk_states').load('nireland-cities.html');
break;
default:
}
});
$('#uk_states').change(function () {
let stateSelected = $(this).val();
let responseStatus = 'success';
getTheWeatherData(stateSelected);
});
[我认为使用switch语句是太多代码,我在某些网站上看到了更好的方法来简化switch语句,甚至转换为对象文字,例如在...上显示的一些示例]]
// Store the input and output in an object
let locations = {
England:"england",
Scotland:"scotland",
Wales:"wales",
"Northern Ireland":"nireland"
};
let county = $('#Uk_Cities option:selected').text();
// Just load the correct document by building the string based on
// looking up the key in the object
$('#uk_states').load(locations[county] + '-cities.html');
$('#uk_states').change(function () {
let stateSelected = $(this).val();
let responseStatus = 'success';
getTheWeatherData(stateSelected);
});