有什么方法可以替换这个对象的 switch 语句吗?
Object.keys(data).forEach(key => {
switch (true) {
case key === '1':
Store.get1();
return;
case key === '2':
get2();
return;
case key === '4':
get4(4);
return;
case key === '5':
get5({value1 = 5.value1, value2 = 5.value2});
return;
default:
break;
}
})
用这样的东西替换它:
Object.keys(data).forEach(key => {
const keyMap = {
1: Store.get1(),
2: get2(),
3: get3(),
4: get4(),
5: get5({value1 = 5.value1, value2 = 5.value2}),
};
return keyMap[key];
但是这样每次都会触发 keyMap 中的每个函数。
- 我需要不带存储的 get2(),因为它只是上层作用域中的一个函数。
- 将 5 想象成一个对象 5:{ value1: something, value2: something}
最佳答案
撇开原文的语法错误,只需要查找表中的函数,然后调用它们:
const keyMap = {
1: Store.get1,
2: get2,
3: get3,
4: get4,
5: get5,
};
Object.keys(data).forEach(key => {
return keyMap[key]();
});
关于javascript - 替换 switch 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54983345/