Reputation: 7123
How can I set multiple conditions for switch statement in JS?
or How to set or condition inside switch?
eg:
switch(apple.amount) or switch(orange.amount)
{
case '1 kg':
total = 100;
break;
case '2 kg':
total = 200;
break;
}
Upvotes: 0
Views: 1686
Reputation: 94499
Use a 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;
}
}
If your certain that only one will have a value during any execution you can use the ||
operator:
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);
Upvotes: 2
Reputation: 108500
Put the switch in a function and test the return value:
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
}
Upvotes: 0