如何在JS中为switch语句设置多个条件?
或如何在开关内设置或调节?
例如:
switch(apple.amount) or switch(orange.amount)
{
case '1 kg':
total = 100;
break;
case '2 kg':
total = 200;
break;
}
答案 0 :(得分:2)
使用loop
:
var amounts = [apple.amount, orange.amount];
var totals = [];
for(var i = 0; i < amounts.length; i++){
switch(amounts[i])
{
case '1 kg':
totals[i] = 100;
break;
case '2 kg':
totals[i] = 200;
break;
}
}
如果您确定在执行期间只有一个人有值,您可以使用||
运算符:
var amount1;
var amount2 = '2 kg';
var total;
switch(amount1 || amount2 )
{
case '1 kg':
total = 100;
break;
case '2 kg':
total = 200;
break;
}
alert(total);
答案 1 :(得分:0)
将开关置于一个函数中并测试返回值:
function getTotal(amount) {
switch(amount) {
case '1 kg':
return 100
case '2 kg':
return 200
}
}
if(getTotal(apple.amount) || getTotal(orange.amount)) {
// both returns a total
}