JavaScript条件切换语句
有没有办法在javascript中编写条件切换语句?
我猜不是,因为以下总是默认:
var raw_value = 11.0; switch(raw_value) { case (raw_value > 10.0): height = 48; width = 36; break; case (raw_value > 5.0): height = 40; width = 30; break; default: height = 16; width = 12; break; }
如果不是,我应该使用什么 – 一个长的if / else语句?
谢谢 :)
在一个switch语句中 , switchexpression式的评估值与案例的评估值进行比较。 所以这里raw_value (number)的值与raw_value > 10.0 (比较expression式)和raw_value > 5.0 (比较expression式)进行比较。
所以,除非你的caseexpression式中的一个产生了一个等于11.0的数字,或者你使用了switchexpression式,否则你将总是得到默认的情况。
只需使用一个简单的if / else来代替:
var raw_value = 11.0; if (raw_value > 10.0) { height = 48; width = 36; } else if (raw_value > 5.0) { height = 40; width = 30; } else { height = 16; width = 12; }
喜欢这个:
var raw_value = 11.0; switch(true) { case (raw_value > 10.0): height = 48; width = 36; break; case (raw_value > 5.0): height = 40; width = 30; break; default: height = 16; width = 12; }
case语句中的expression式将计算为true或false ,如果符合switch条件…voilà。 default行为像一个else 。
奖金:您可以通过简单地将truereplace为false来反转整个逻辑。 使用if ... else if语句,您将不得不单独编辑每个if-clause。
不, switch语句不起作用。 但是,这种说法并不总是比较简单。 例如, switch版本需要15行:
var raw_value = 11.0; switch(raw_value) { case (raw_value > 10.0): height = 48; width = 36; break; case (raw_value > 5.0): height = 40; width = 30; break; default: height = 16; width = 12; break; }
和“长” if/else版本只有 11:
var raw_value = 11.0; if (raw_value > 10.0) { height = 48; width = 36; } else if (raw_value > 5.0) { height = 40; width = 30; } else { height = 16; width = 12; }
所以在你的情况下,最好使用第二个比第一个…
不要在家里尝试,或认真对待,这只是为了好玩。
function conditionalSwitch( value, cond, callback /* cond, callback, cond, callback, ... */ ) { for (var i = 1; i < arguments.length; i += 2) { if ( arguments[i](value) ) { arguments[i+1](value); return; } } } var width, height; conditionalSwitch( 5.1, function(val) { return val > 10 }, function () { height = 48; width = 36 }, function(val) { return val > 5 }, function () { height = 40; width = 30 }, //Default function(val) { return true }, function () { height = 16; width = 12; } ) console.log(width, height);