Javascript:如何为基于表达式的条件使用对象文字而不是 if 和 switch 语句? [英] Javascript: How to use object literals instead of if and switch statements for expression-based conditions?
本文介绍了Javascript:如何为基于表达式的条件使用对象文字而不是 if 和 switch 语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 javascript 中,我至少要考虑使用嵌套对象字面量树作为我的控制流,而不是 if 语句、switch 语句等.
In javascript, I want to at least consider using a nested object literal tree for my control flow instead of if statements, switch statements, etc.
下面是一个使用 if 语句的函数转换为使用对象字面量完成相同功能的函数的示例.
Below is an example of a function using if statements turned into a function using object literals to accomplish the same functionality.
// if & else if
function getDrink (type) {
if (type === 'coke') {
type = 'Coke';
} else if (type === 'pepsi') {
type = 'Pepsi';
} else if (type === 'mountain dew') {
type = 'Mountain Dew';
} else {
// acts as our "default"
type = 'Unknown drink!';
}
return type;
}
// object literal
function getDrink (type) {
var drinks = {
'coke': function () {
return 'Coke';
},
'pepsi': function () {
return 'Pepsi';
},
'Mountain Dew': function () {
return 'Mountain dew';
},
'default': function () {
return 'Unknown drink!';
}
};
return (drinks[type] || drinks['default'])();
}
这在测试简单值时有效,但如何将以下 switch 语句转换为对象字面量控制结构?
This works when testing for a simple value, but how could I turn the following switch statement into an object literal control structure?
switch (true) {
case (amount >= 7500 && amount < 10000):
//code
break;
case (amount >= 10000 && amount < 15000):
//code
break;
//etc...
推荐答案
一个使用 Array.find 的小帮手可能会有用:
A small helper usong Array.find might be useful:
const firstCase = (...cases) => value => cases.find(c=> c[0](value))[1];
可用作:
const dayTime = firstCase(
[t => t < 5, "night"],
[t => t < 12, "morning"],
[t => t < 18, "evening"],
[true, "night"]
);
console.log(dayTime(10)); // morning
这也适用于函数:
const greetAtTime = firstCase(
[t => t < 10, name => `Good morning ${name}!`],
[t => t > 18, name => `Good evening ${name}!`],
[true, name => `Hello ${name}!`]
);
console.log(greetAtTime(12)("Jack"));
这篇关于Javascript:如何为基于表达式的条件使用对象文字而不是 if 和 switch 语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文