Javascript开关无法解析整数

时间:2016-03-14 13:47:51

标签: javascript switch-statement

我似乎无法使我的第二个开关工作,它看起来与第一个开关工作正常相同,并且第二个开关后的一切工作正常。我无法获得变量'折扣百分比'根据案例进行更新。 (它只是一个单一的每周任务)任何想法?

function ticketQ() {
var ticketType=prompt("What type of tickets do you want?")
var ticketQty=parseInt(prompt("How many tickets do you want?"))
document.write("The ticket type is " +ticketType +"<br>")
document.write("The ticket quantity is " +ticketQty +"<br>")
var ticketPrice=parseInt(0);
switch(ticketType) {
    case (ticketType="A"):
         var ticketPrice=parseInt(100)
         break;
    case (ticketType="B"):
        var ticketPrice=parseInt(75)
        break;
    case (ticketType="C"):
        var ticketPrice=parseInt(50)
        break;
    default:
    document.write("Invalid ticket type" +"<br>");
        break;
}
if (ticketQty >100 || ticketQty <1){
document.write("InvalidQty" +"<br>")
}if (ticketPrice >0 && ticketQty >0 && ticketQty <100){
var grossAmount=parseInt(ticketPrice * ticketQty)
}
var discountPercent=parseInt(0);
switch(grossAmount) {
    case (grossAmount >200):
         var discountPercent=parseInt(50);
         break;
    case (grossAmount >200):
        var discountPercent=parseInt(5);
        break;
//      case (grossAmount ):
//          var discountPercent=parseInt()
 //         break:
 //     case (grossAmount ):
//          var discountPercent=parseInt()
//          break;
    default:
    document.write("wrong" +"<br>")
    break;
}

var discountAmount=parseInt((discountPercent / 100) *grossAmount)
var nettAmount=parseInt(grossAmount - discountAmount)
document.write("Gross Amount: $" + grossAmount + "<br>")
document.write("Discount Percent: " + discountPercent + "%" + "<br>")
document.write("Discount Amount: $" + discountAmount + "<br>")
document.write ("Nett Amount: $" + nettAmount + "<br>")
}

1 个答案:

答案 0 :(得分:0)

您的switch语句不正确。以下是一些可行的方法

switch(ticketType) {
    case ("A"):
         var ticketPrice=parseInt(100)
         break;
    case ("B"):
        var ticketPrice=parseInt(75)
        break;
    case ("C"):
        var ticketPrice=parseInt(50)
        break;
    default:
    document.write("Invalid ticket type" +"<br>");
        break;
}


switch(true) {
    case (grossAmount >400):
         var discountPercent=parseInt(50);
         break;
    case (grossAmount >200):
        var discountPercent=parseInt(5);
        break;
    default:
    document.write("wrong" +"<br>")
    break;
}

请参阅http://www.ecma-international.org/ecma-262/5.1/#sec-12.11获取完整的低位,或者http://www.w3schools.com/js/js_switch.asp获取更简单的示例