Пример использования if/else
function getTranslation(rhyme) {
if (rhyme.toLowerCase() === "apples and pears") {
return "Stairs";
} else if (rhyme.toLowerCase() === "hampstead heath") {
return "Teeth";
} else if (rhyme.toLowerCase() === "loaf of bread") {
return "Head";
} else if (rhyme.toLowerCase() === "pork pies") {
return "Lies";
} else if (rhyme.toLowerCase() === "whistle and flute") {
return "Suit";
}
return "Rhyme not found";
}
toLowerCase()
Пример использования switch
function getTranslation(rhyme) {
switch (rhyme.toLowerCase()) {
case "apples and pears":
return "Stairs";
case "hampstead heath":
return "Teeth";
case "loaf of bread":
return "Head";
case "pork pies":
return "Lies";
case "whistle and flute":
return "Suit";
default:
return "Rhyme not found";
}
}
break
Решение с использованием объектных литералов
function getTranslation(rhyme) {
const rhymes = {
"apples and pears": "Stairs",
"hampstead heath": "Teeth",
"loaf of bread": "Head",
"pork pies": "Lies",
"whistle and flute": "Suit",
};
return rhymes[rhyme.toLowerCase()] ?? "Rhyme not found";
}
??
Пример использования нулевого слияния
null
undefined
false
0
function stringToBool(str) {
const boolStrings = {
"true": true,
"false": false,
};
return boolStrings[str] ?? "String is not a boolean value";
}
Более сложные условия с функциями
function calculate(num1, num2, action) {
const actions = {
add: (a, b) => a + b,
subtract: (a, b) => a - b,
multiply: (a, b) => a * b,
divide: (a, b) => a / b,
};
return actions[action]?.(num1, num2) ?? "Calculation is not recognised";
}
?.