简体   繁体   中英

How to assign the result of a conditional decision to a variable in javascript

The following code works fine:

    var styles = []
    if (state == 's1') {
        styles = ['inline-block', 'none', 'none']
    } else if (state == 's2') {
        styles = ['none', 'inline-block', 'none']
    } else if (state == 's3') {
        styles = ['none', 'none', 'inline-block']
    }

However in some languages we can make this more concise. I would like to do something along the following lines:

    var styles = 
      if (state == 's1') {
          ['inline-block', 'none', 'none']
      } else if (state == 's2') {
          ['none', 'inline-block', 'none']
      } else if (state == 's3') {
          ['none', 'none', 'inline-block']
      }

Is there such a conditional assignment - or even better some kind of match/case - in javascript?

Update Lots of good answers - thanks! Chose one seems closest to my original intent. But learnt a variety of aspects of javascript across many of them.

You can define the conditions as a function

chooseStyle = (state) => {
    if (state == 's1') {
        return ['inline-block', 'none', 'none']
    } else if (state == 's2') {
        return ['none', 'inline-block', 'none']
    } else if (state == 's3') {
        return ['none', 'none', 'inline-block']
    }
}

var styles = chooseStyle(state)

Or even better if you use a switch instead:

chooseStyle = (state) => {
    switch(state) {
        case 's1':
            return ['inline-block', 'none', 'none']
        case 's2':
            return ['none', 'inline-block', 'none']
        case 's3':
            return ['none', 'none', 'inline-block']
        default:
            return ['inline-block', 'none', 'none'] // return the default styles you want, here I choose the styles of 's1'
    }
}

You could take an array of states and map either 'inline-block' for a value at this index or 'none' .

 const order = ['s1', 's2', 's3'], getStyles = state => order.map(v => v === state ? 'inline-block' : 'none'); console.log(...getStyles('s1')); console.log(...getStyles('s2')); console.log(...getStyles('s3'));

Like many languages whose syntax is patterned after C, JavaScript has conditional expressions (aka "tertiary") that can be used for simple if-then-else conditions.

condition ? true-value : false-value

You can nest these for multiple cases, but it tends to become unreadable.

var styles = state == 's1' ? ['inline-block', 'none', 'none'] :
    (state == 's2' ? ['none', 'inline-block', 'none'] : ['none', 'none', 'inline-block']);

There's no analogous expression form of case . But you could use an object:

const style_mappings = {
    "s1": ['inline-block', 'none', 'none'],
    "s2": ['none', 'inline-block', 'none'],
    "s3": ['none', 'none', 'inline-block']
};
var styles = style_mappings[state];

Use a mapping object:

const styleMap = {
  s1: ['inline-block', 'none', 'none'],
  s2: ['none', 'inline-block', 'none'],
  s3: ['none', 'none', 'inline-block'],
};

const styles = styleMap[state];

JavaScript doesn't have anything exactly like that, but one solution which gets pretty close is to store the results in an object/dictionary and call it with the state you want:

 const styles = { 's1': ['inline-block', 'none', 'none'], 's2': ['none', 'inline-block', 'none'], 's3': ['none', 'none', 'inline-block'] } console.log(`s1: ${styles['s1']}`) console.log(`s2: ${styles['s2']}`) console.log(`s3: ${styles['s3']}`)

You could use the switch statement in JavaScript to accomplish this. Your code would be something like this

var styles = ['none', 'none', 'none'];
switch (state) {
    case 's1':
        styles[0]='inline-block';
        break;
    case 's2':
        styles[1]='inline-block';
        break;
    case 's3':
        styles[2]='inline-block';
        break;
}

You could use a tenary javascript operator. So the code may look like so:

var styles = (state == 's1')? 
                        ['inline-block', 'none', 'none']:  (state == 's2')? 
                                                            ['none', 'inline-block', 'none']: (state == 's3')?
                                                                                              ['none', 'none', 'inline-block']:[]; 

Usage example:

Example 1:
var state = 's1'; 
console.log(styles);  //outputs [ "inline-block", "none", "none" ]
Example 2: 
var state = 's2'; 
console.log(styles);  //outputs [ "none", "inline-block", "none" ]
Example 3: 
var state = 's3'; 
console.log(styles);  //outputs [ "none", "none", "inline-block" ]
Example 4: 
var state = 's'//a state without a match
console.log(styles);  //outputs []

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM