[英]Object based switch alternative in javascript
I tend to use expression like this these days:这些天我倾向于使用这样的表达方式:
{ typeA: 'some code' }[type] ||
{ typeB: 'some other code' }[type] ||
defaultType
How do I fairly simple put multiple cases (something like:我如何相当简单地放置多个案例(例如:
switch (value)
{
case typeA:
case typeC:
//do some stuff
break;
case typeB:
//do some other stuff
default:
//default stuff
break;
}
) in the code above? ) 在上面的代码中? So it could work this way ( invalid piece of code):
所以它可以这样工作(无效的代码段):
{ typeA || typeC: 'some code' }[type] ||
{ typeB: 'some other code' }[type] ||
defaultType
Backstory: I am utilising the code in React, so the 'some code' samples are actually React components.背景故事:我正在使用 React 中的代码,所以“一些代码”示例实际上是 React 组件。
You're halfway there already.你已经成功了一半。 Just combine your objects into a big one:
只需将您的对象组合成一个大对象:
return ({
typeA: "Foo",
typeB: "Bar",
get typeC() {//why not getters?
return "computed value"
},
}[value]) || defaultValue;
I strongly recommend saving the case-object as a const or it'll re-allocate on every call.我强烈建议将 case-object 保存为 const ,否则它会在每次调用时重新分配。
This structure is suitable for values, but not conditional logic.这种结构适用于值,但不适用于条件逻辑。 If you need to execute different code on each
case
, you should either stick with switch
, or make your object return functions:如果您需要在每种
case
执行不同的代码,您应该坚持使用switch
,或者让您的对象返回函数:
const Values = {
caseA: () => { /*...*/ },
caseB: () => { /*...*/ },
// ...etc
}
//get value from Values and execute function
Values['caseA']();
With this structure you don't get fall-through.使用这种结构,您不会落空。 If you want fall-through, stick with
switch
.如果你想要失败,坚持使用
switch
。
Define your switch-like object:定义类似开关的对象:
const types = {
typeA: 'some code',
...
}
Then call it:然后调用它:
types[type] || defaultType
You can also include the default value in the switch-lick object:您还可以在 switch-lick 对象中包含默认值:
const types= {
typeA: 'some code',
...,
default: 'some code for default type',
}
Later:之后:
types[type] || types.default
If you are using functions as values:如果您使用函数作为值:
(types[type] && types[type](args)) || types.default()
You could combine the objects into a single one, the first one at last, to keep the values from the first and take type
as accessor.您可以将对象合并为一个,最后一个,以保留第一个中的值并将
type
作为访问器。
For using an alias, you need to specify a new property for it.要使用别名,您需要为其指定一个新属性。
result = { ...objectB, ...objectA, typeC: objectA.typeA }[type] || defaultValue;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.