Alternative to the “switch” Statement

后端 未结 8 2076
眼角桃花
眼角桃花 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:43

    You could use object literals, and try catch to trap the default:

    function write(what) {
        var colors = {
        'Blue': function(){ alert('Light-Blue'); },
        'Red': function(){ alert('Deep-Red'); },
        'Green': function(){ alert('Deep-Green'); }
        }
        try {colors[what]();}
        catch(err) {colors['Green']();}//default behaviour
    }
    write('Pink');
    

提交回复
热议问题