Alternative to the “switch” Statement

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

    I used a structure like this today:

    var chosenColor = 'red';
    
    var colorString = {
        'red': 'The color is red.',
        'green': 'The color is green.',
        'blue': 'The color is blue.',
    }[chosenColor] || 'The color is unknown.';
    

    I like that it's a really small amount of code to choose a string based on choice.

    You could also pass it to a function:

    alert({
        'red': 'The color is red.',
        'green': 'The color is green.',
        'blue': 'The color is blue.',
    }[chosenColor] || 'The color is unknown.');
    

提交回复
热议问题