Javascript 嵌套开关盒
我当前收到一个错误,或者没有显示任何内容。请帮忙Javascript 嵌套开关盒,javascript,Javascript,我当前收到一个错误,或者没有显示任何内容。请帮忙 function getTotal() { var service = prompt("What service would you like? ", " "); var options = prompt("How frequent do you want the service? ", " "); var contractLength = prompt("How long do you want the contract?" , " "); v
function getTotal()
{
var service = prompt("What service would you like? ", " ");
var options = prompt("How frequent do you want the service? ", " ");
var contractLength = prompt("How long do you want the contract?" , " ");
var totalPrice = " ";
switch (service) {
case 'Lawn Maintenance':
switch (options) {
case 'Montly':
switch (contractLength) {
case '6':
totalPrice = $25 }
}
break; }
开关,尤其是嵌套开关,将使事情变得比需要的复杂得多,难以阅读。考虑使用由选项索引的对象,例如:
function getTotal() {
var service = prompt("What service would you like? ", " ");
var frequency = prompt("How frequent do you want the service? ", " ");
var contractLength = prompt("How long do you want the contract?", " ");
const services = {
'Lawn Maintenance': {
'Monthly': {
'3': 15,
'6': 25
},
'Yearly': {
'3': 5,
'6': 10
}
// etc
}
}
const serviceObj = services[service];
if (!serviceObj) throw new Error('Invalid service');
const frequencyObj = serviceObj[frequency];
if (!frequencyObj) throw new Error('Invalid frequency');
const totalPrice = frequencyObj[contractLength];
if (totalPrice === undefined) throw new Error('Invalid contract length');
return '$' + totalPrice;
}
总价=25美元。。。你有一个叫做$25的变量吗?