preface
A few days ago, I was responsible for the preparation of the website online environmental judgment function, which involves a large number of multi-condition judgment code. For multi-conditional writing, most programmers use if… else if… Or else the switch… Case, but there is a more interesting and elegant multi-condition method than the traditional one — object attribute method.
Examples show
Without further ado, the following direct use of three examples, to show you three different multi-conditional judgment writing methods.
1. if... else if... else
function whatFood(mealtime) {
let food = ' ';
if (mealtime === 'breakfasttime') {
food = 'egg';
} else if (mealtime === 'lunchtime') {
food = 'vegetable'
} else if (mealtime === 'dinnertime') {
food = 'fruit'
} else {
food = 'cookie'
}
return food;
}
Copy the code
2. switch... case
function whatFood(mealtime) {
let food = ' ';
switch (mealtime) {
case 'breakfasttime':
food = 'egg';
break;
case 'lunchtime':
food = 'vegetable';
break;
case 'dinnertime':
food = 'fruit';
break;
default:
food = 'cookie';
}
return food;
}
Copy the code
3. Object attribute judgment method
function whatFood(mealtime) {
const food = {
breakfasttime: 'egg',
lunchtime: 'vegetable',
dinnertime: 'fruit'
}
return food[mealtime] ? food[mealtime] : 'cookie';
}
Copy the code
conclusion
I believe you have seen the advantages and disadvantages of different writing methods through the above three examples. If you have a better multi-conditional writing method, please leave a comment and discuss it. Wish you a smooth work and a happy life.