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?" , " ");
var totalPrice = " ";
switch (service) {
case 'Lawn Maintenance':
switch (options) {
case 'Montly':
switch (contractLength) {
case '6':
totalPrice = $25 }
}
break; }
解决方案
switch
es,尤其是嵌套的,将使事情变得比他们需要的更复杂和难以阅读。考虑使用由选项索引的对象,例如:
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;
}
推荐阅读
- python - 您可以使用 protobuf 将 iframe 标签序列化为二进制数据吗?
- python - 如何使用python在谷歌搜索结果中打开一个网站?
- git - 多个目录中的相同单词文件,多个用户没有管理员权限
- r - 计算连续失败及其开始和结束日期
- android - 如何在不使用 Intent 的情况下将事件添加到 Android 设备上的日历
- spring-webflux - 如何使用 Reactor (Spring WebClient) 模拟 for 循环
- sql - 使用 TSQL 在 SQL Server 中使用单引号和逗号将短语拆分为单词
- python - 无论如何我们只能从图像轴中提取文本吗?
- javascript - 将 Jquery 添加到 AMP 页面
- excel - 如何从 2 个查找值单元格中使用 vlookup