Alternative to the “switch” Statement

后端 未结 8 2049
眼角桃花
眼角桃花 2020-12-04 20:15

I do not want to use Switch in my code, so I\'m looking for some alternative

Example with Switch:

function write(what) {

  switch(w         


        
相关标签:
8条回答
  • 2020-12-04 20:45

    Question 2:

    Generally, if you can replace custom control structures with a dictionary lookup, you're perfectly fine. It's easy to read and highly elegant -- stick with it.

    0 讨论(0)
  • 2020-12-04 20:49

    As I said, it's great. The only thing I can add to your solution is that it's perhaps better to localize your colors.

    function write(what) {
        var colors = [];
        colors['Blue'] = function() { alert('Blue'); };
        colors['Red'] = function() { alert('Red'); };
        colors[what]();
    }
    
    0 讨论(0)
提交回复
热议问题