So I've been using switch statements, and was wondering if there is a way to get several strings into one case, instead of only one string per case.
For example:
switch(fruits) {
case 'apples','bananas','oranges','strawberries':
//I'd like to get those four fruits into one case, instead of doing this:
switch (fruits) {
case 'apples':
break;
case 'bananas':
break;
case 'oranges':
break;
case 'strawberries':
If this can be done it will save me a lot of time.
Use it like:
switch (fruits) {
case 'apples':
case 'bananas':
case 'oranges':
case 'strawberries':
//Your code
break;
}
Do not use switch/case when you need multiple value matches. Use IF
:
if(fruits === 'apples' ||
fruits === 'bananas' ||
fruits === 'oranges' ||
fruits === 'strawberries'){
//do some action
}
You could avoid the switch
altogether: store all the fruits in an array and then use some
to see if the fruit is there:
var arr = ['apples', 'bananas', 'oranges', 'strawberries'];
function check(arr, fruit) {
return arr.some(function (el) {
return el.indexOf(fruit) > -1;
});
}
if (check(arr, 'oranges') {
// do stuff if true
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.