2014-07-11 89 views
-1

此代碼旨在使用開關語句創建修改後的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); 
+0

'switch(true){' –

+0

要澄清一點,對應於該情況的函數應該向對象liftStats,liftStats.muscleBMI添加一個新屬性。在每種情況下,屬性應該等於userStats對象的userStats.BMI屬性減去diff(等於450 - 參數,在這種情況下,sum,即311.8),但正如我所說的,它無法創建此屬性並輸出默認值。 – user3826598

+1

不錯的,餅乾怪物。迴應簡潔的額外點 - 這是道德觀點,我沒有代表:p – user3826598

回答

1

case S的值進行比較,以在switch值。所以,你正在檢查diff == (diff < 180 && diff > 120),這是diff == truediff == false

使用if/elses或switch(true)

+0

+1我認爲if/else建議是一個好的建議。 –