切换语句和功能

时间:2014-07-11 16:01:28

标签: javascript function variables object switch-statement

此代码旨在使用switch语句创建修订的BMI,以计算肌肉质量。我无法理解为什么switch语句不起作用。我已经控制台记录了作为switch语句一部分的所有值,但由于某种原因,它总是返回默认响应。如果有人能让我深入了解为什么这不起作用,我将不胜感激。

var heightInputFeet = 5;     var inches = 11;     var footToMeter = parseFloat((heightInputFeet * 0.3048)+(0.3048 / 12)* inches).toFixed(2);     var inputWeight = 82;

var bench = 30;
var squat = 60;
var curl = 25;
var pullUps = 24;

var liftStats = new Object();
liftStats.bench = bench;
liftStats.squat = squat;
liftStats.curl = curl;
liftStats.pullUps = pullUps;
liftStats.pullUpPower = (pullUps * inputWeight) / 10;

function baseStats() {
    this.height = footToMeter;
    this.weight = inputWeight;
    this.BMI = this.weight / Math.pow(footToMeter, 2);
}
var userStats = new baseStats();

var sum = bench + squat + curl + liftStats.pullUpPower;  // sum equals 311.8

function revisedBMI(n){    //38 - 54
var diff = 450 - n; // 
    switch(diff){
        case (diff < 180 && diff > 120):
            function lower() {
                return liftStats.muscleBMI = userStats.BMI - (diff / 50);
            }
            lower();
            break;
        case (diff > 60 && diff < 120):
            function mid(){
                return liftStats.muscleBMI = userStats.BMI - (diff / 50);
            }
            mid();
            break;
        case (diff < 60 && diff > 0):
            function adv(){
                return liftStats.muscleBMI = userStats.BMI - (diff / 50);
            }
            adv();
            break;
        case (diff < 0):
            function mega(){
                return liftStats.muscleBMI = userStats.BMI - (diff / 50);

            }
            mega();
            break;
        default: console.log("please enter a value...");
            break;
    }
}
revisedBMI(sum);

1 个答案:

答案 0 :(得分:1)

case的值与switch中的值进行比较。因此,您需要检查diff == (diff < 180 && diff > 120)diff == truediff == false

使用if / elses或switch(true)