Alternative to the quot;switchquot; Statement(“开关的替代方案陈述)
问题描述
我不想在我的代码中使用 Switch,所以我正在寻找一些替代方法
I do not want to use Switch in my code, so I'm looking for some alternative
开关示例:
function write(what) {
switch(what) {
case 'Blue':
alert ('Blue');
break;
...
case 'Red':
alert ('Red');
break;
}
}
不带开关的示例:
colors = [];
colors['Blue'] = function() { alert('Blue'); };
colors['Red'] = function() { alert('Red'); };
function write(what) {
colors[what]();
}
我的问题是:
- 您知道其他替代方案吗?
- 这是最好的解决方案吗?
推荐答案
我只有一个关于你的第二种方法的注释,你 不应使用数组 来存储非数字索引(在其他语言中您可以将其称为关联数组).
I have only a note about your second approach, you shouldn't use an Array to store non-numeric indexes (that you would call in other languages an associative array).
你应该使用一个简单的对象.
You should use a simple Object.
此外,您可能需要检查传递给 write
函数的 what
参数是否作为 colors
对象的属性存在并查看如果它是一个函数,那么您可以在没有运行时错误的情况下调用它:
Also, you might want to check if the what
argument passed to your write
function exists as a property of your colors
object and see if it's a function, so you can invoke it without having run-time errors:
var colors = {};
colors['Blue'] = function() { alert('Blue'); };
colors['Red'] = function() { alert('Red'); };
function write(what) {
if (typeof colors[what] == 'function') {
colors[what]();
return;
}
// not a function, default case
// ...
}
这篇关于“开关"的替代方案陈述的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:“开关"的替代方案陈述


基础教程推荐
- 我可以在浏览器中与Babel一起使用ES模块,而不捆绑我的代码吗? 2022-01-01
- Vue 3 – <过渡>渲染不能动画的非元素根节点 2022-01-01
- 如何使用TypeScrip将固定承诺数组中的项设置为可选 2022-01-01
- 直接将值设置为滑块 2022-01-01
- 如何使用JIT在顺风css中使用布局变体? 2022-01-01
- 用于 Twitter 小部件宽度的 HTML/CSS 2022-01-01
- Electron 将 Node.js 和 Chromium 上下文结合起来意味着 2022-01-01
- Chart.js 在线性图表上拖动点 2022-01-01
- html表格如何通过更改悬停边框来突出显示列? 2022-01-01
- 自定义 XMLHttpRequest.prototype.open 2022-01-01