Javascript 在没有if语句的情况下,根据条件执行不同的函数
是否有更好的方法/编码方式在不同的条件下执行不同的函数而不使用if语句 我一直在用JavaScript以以下方式编码:(例如,不同条件下的函数可能使用不同的API获取方法) 我曾想过使用Javascript 在没有if语句的情况下,根据条件执行不同的函数,javascript,performance,coding-style,Javascript,Performance,Coding Style,是否有更好的方法/编码方式在不同的条件下执行不同的函数而不使用if语句 我一直在用JavaScript以以下方式编码:(例如,不同条件下的函数可能使用不同的API获取方法) 我曾想过使用eval(),但这是一个好方法吗?例如,创建对象包括作为条件的键和作为属性的函数名 conditions:{ a: 'foo', b: 'bar', c: 'foo_2', d: 'bar_2', } 然后像eval(this.conditions[a])一样运行它 但我也听说使用eval进行测
eval()
,但这是一个好方法吗?例如,创建对象包括作为条件的键和作为属性的函数名
conditions:{
a: 'foo',
b: 'bar',
c: 'foo_2',
d: 'bar_2',
}
然后像eval(this.conditions[a])一样运行它
但我也听说使用eval
进行测试很困难。您可以使用key来指向函数标识符。您最好使用键指向功能:
conditions:{
a: () => {
// body of foo
},
b: () => {
// body of bar
},
c: () => {
// body of foo_2
},
d: () => {
// body of bar_2
}
}
conditions[ your_key ]();
您可以使用键指向函数标识符。您最好使用键指向功能:
conditions:{
a: () => {
// body of foo
},
b: () => {
// body of bar
},
c: () => {
// body of foo_2
},
d: () => {
// body of bar_2
}
}
conditions[ your_key ]();
是的,您可以使用函数构建条件对象并调用它们:
function foo(){...}
function bar(){...}
var conditions : {
'a': foo,
'b': bar,
}
conditions[answer]()
注意:尽可能不要使用eval
,如果您不知道自己在做什么,可能会有安全风险是的,您可以使用该函数构建条件对象并调用它们:
function foo(){...}
function bar(){...}
var conditions : {
'a': foo,
'b': bar,
}
conditions[answer]()
注意:尽可能不要使用eval
,如果您不知道自己在做什么,就会有安全风险您可以定义对函数的引用或在每个条件下执行的引用
const doSomething = (args) => {
// do something
}
const doSomethingElse = (args) => {
// do something else
}
const conditions = {
a: doSomething,
b: doSomethingElse
};
// and then
const result = conditions[answer](params);
甚至函数引用的列表
const conditions = {
a: [
doSomething,
],
b: [
doSomething,
doSomethingElse
]
};
// and then
const results = conditions[ answer ].map(method => method());
您可以定义对函数的引用,也可以在每个条件下执行
const doSomething = (args) => {
// do something
}
const doSomethingElse = (args) => {
// do something else
}
const conditions = {
a: doSomething,
b: doSomethingElse
};
// and then
const result = conditions[answer](params);
甚至函数引用的列表
const conditions = {
a: [
doSomething,
],
b: [
doSomething,
doSomethingElse
]
};
// and then
const results = conditions[ answer ].map(method => method());
您可以创建如下函数:
this['some answer'] = function() {...}
然后像这样称呼它
this[answer]()
您可以创建如下函数:
this['some answer'] = function() {...}
然后像这样称呼它
this[answer]()
不要存储带有函数名和eval
的字符串。只需存储函数本身,并调用它们!不要存储带有函数名和eval
的字符串。只需存储函数本身,并调用它们!