2017-03-17 72 views
0

可以使此語句的縮短版本成爲可能嗎?我知道,有簡寫switch語句,如果情況像1,2,3等針對複雜情況的開關語句的較短版本

var direction = pos[i].direction; 
    switch (true) { 
     case (direction >= 0 && direction < 22): 
      graphic = "/img/0.png" 
      break; 
     case (direction >= 22 && direction < 45): 
      graphic = "/img/225.png" 
      break; 
     case (direction >= 45 && direction < 67): 
      graphic = "/img/450.png" 
      break; 
     case (direction >= 67 && direction < 90): 
      graphic = "/img/675.png" 
      break; 
     default: 
      graphic = "/img/0.png" 
      break; 
    } 

回答

3

你可以省略第一次檢查,因爲值已經前檢查。

switch (true) { 
    case direction < 22: 
     graphic = "/img/0.png"; 
     break; 
    case direction < 45: 
     graphic = "/img/225.png"; 
     break; 
    case direction < 67: 
     graphic = "/img/450.png"; 
     break; 
    case direction < 90: 
     graphic = "/img/675.png"; 
     break; 
    default: 
     graphic = "/img/0.png"; 
     break; 
} 
+2

嗨,你也可以省略第一種情況,因爲它是默認的。 –

+2

否,那麼您需要檢查大於或等於'22',另外小於'45'。 –

+1

看起來,'graphic =「/img/0.png」是缺省值,或者是小於22的值,或者是大於/等於90。 –

-1

你應該使用,否則因爲你有條件準備好you.so,不需要使用開關盒。