Alternative to the “switch” Statement

后端 未结 8 2051
眼角桃花
眼角桃花 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条回答
  •  -上瘾入骨i
    2020-12-04 20:45

    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.

    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
      // ...
    }
    

提交回复
热议问题