Alternative to the “switch” Statement

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

    You are pretty much there already. If possible you might want to add a helper function to make the setup easier. For Example:

    function setup(what)
    {
        colors[what] = function() { alert(what); };
    }
    

    EDIT:
    If what you want to do for each option is more complicated clearly this will not work. As mentioned in the comments by @roe this uses the global colors which is often frowned upon.

提交回复
热议问题