我在JavaScript switch语句中做错了什么?

时间:2014-12-27 12:49:49

标签: javascript switch-statement

下面我有各种输入字段,我根据初始收入值计算月末收益和年收益的最终结果。

我要做的是添加单选按钮以选择天气,他们插入的值是每周,每月等...

我发布了第一个收入值的例子,我需要用户决定使用复选框......

function computeBudget() {        
        var income = document.getElementById('income').value;
        switch(rate) {
            case weekly:
                this.add((.value * 52) / 12);
                break;
            case biWeekly:
                this.add((.value * 26) / 12);
                break;
        }

        var grocery_expenses = document.getElementById('grocery_expenses').value;
        var car_insurance = document.getElementById('car_insurance').value;
        var home_mortgage = document.getElementById('home_mortgage').value;
        var home_utilities = document.getElementById('home_utilities').value;
        var life_insurance = document.getElementById('life_insurance').value;


        var monthgain = (income - grocery_expenses - car_insurance - home_mortgage - home_utilities -life_insurance).toFixed(2);
        monthgain = monthgain.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
        document.getElementById('monthgain').innerHTML = "Monthly Net Gain = $"+monthgain ;

        var yeargain = ((income - grocery_expenses - car_insurance - home_mortgage - home_utilities -life_insurance) * 12).toFixed(2);
        yeargain = yeargain.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
        document.getElementById('yeargain').innerHTML = "Yearly Net Gain = $"+ yeargain;
    }

2 个答案:

答案 0 :(得分:0)

尝试在案例值中添加引号,例如:

switch(rate) {
        case "weekly": // added quotes
            this.add((.value * 52) / 12);
            break;
        case "biWeekly": // added quotes
            this.add((.value * 26) / 12);
            break;
    }

答案 1 :(得分:0)

您需要创建一个每周乘数变量,将变换值保持为几周。

然后,您需要打开单选按钮的值,并为您要处理的每种情况创建一个案例。

示例:

var weekMultiplier = 0;
switch(rate) // a string value representing the type
{
    case "weekly":
        weekMultiplier = 1;
        break;
    case "biWeekly":
        weekMultiplier = 0.5;
        break;
    case "monthly":
        weekMultiplier = 0.25;
        break;
}

然后你用这个乘数乘以你的输入。如果它们尚未转换为每周的值,那么您可以为计算中包含的每个值执行此操作。

示例:

var weeklyIncome = income * weekMultiplier;
var weeklyCarInsurance = document.getElementById('car_insurance').value * weekMultiplier;

现在你可以减去它们

var weeklyGain = weeklyIncome - weeklyCarInsurance;

并将所需格式的增益相乘:

var monthlyGain = weeklyGain * 4;
var yearlyGain = weeklyGain * 52;