2017-03-17 77 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,不需要使用开关盒。