[英]Why isn't my jquery switch statement working?
I am trying a jquery (javascript) switch statement with some simple operators but it isn't working as expecting 我正在尝试使用一些简单的运算符进行jquery(javascript)switch语句,但是它没有按预期工作
console.log('test '+getShippingCost(8));
function getShippingCost(shop_qty) {
shipping_costs = 0;
dest = $("input[name='dest']").val();
console.log(dest);
if (dest === 'DOMESTIC') {
switch (shop_qty) {
case (shop_qty > 4):
shipping_costs = 3.5;
break;
case (shop_qty <= 4):
shipping_costs = 2;
break;
}
console.log('domestic shipping '+shipping_costs);
}
if (dest === 'INT') {
switch (shop_qty) {
case (shop_qty > 4):
shipping_costs = 4.5;
break;
case (shop_qty <= 4):
shipping_costs = 3;
break;
}
}
return shipping_costs;
}//end function
see see jsfiddle 请参阅jsfiddle
To use conditions for the cases in a switch
, you would look for a true
value among the cases: 要在
switch
为案例使用条件,您将在案例中寻找true
值:
switch (true) {
case (shop_qty > 4):
shipping_costs = 3.5;
break;
case (shop_qty <= 4):
shipping_costs = 2;
break;
}
As the second case is the inverse of the first, you can just use default
for that: 由于第二种情况与第一种情况相反,因此您可以使用
default
:
switch (true) {
case (shop_qty > 4):
shipping_costs = 3.5;
break;
default:
shipping_costs = 2;
break;
}
Such a construct fits better when you have several conditions. 当您有多个条件时,这样的构造更适合。 You should consider if an
if
statement would be a better fit in this case: 您应该考虑在这种情况下
if
语句是否更合适:
if (shop_qty > 4) {
shipping_costs = 3.5;
} else {
shipping_costs = 2;
}
As both cases assign a value to the same variable, you can also write it using the conditional operator: 由于这两种情况都为同一个变量分配了一个值,因此您也可以使用条件运算符将其写入:
shipping_costs = shop_qty > 4 ? 3.5 : 2;
Switch doesn't work by evaluating boolean expressions. 通过评估布尔表达式,Switch不起作用。 Switch evaluates an initial expression and then tries to match the cases to that expression using strict equality.
Switch会计算初始表达式,然后尝试使用严格相等将个案与该表达式匹配。 So you can't do
所以你做不到
case(x<4.5):
You have to do something like 你必须做类似的事情
case 4:
Use if, else if, else statments instead. 使用if,else if,else语句代替。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.