嵌套开关盒

时间:2018-10-01 00:05:04

标签: 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; }

1 个答案:

答案 0 :(得分:1)

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;
}