简体   繁体   中英

Better way to conditionally access values

I'm wondering if there's a better way to achieve this:

const string = a < b ? 'value 1' : a > c ? 'value 2' : 'value 3'

I would do something like this, but it wouldn't work with conditions.

const string = {
  0: 'value 1',
  1: 'value 2',
}[ ? ] || 'value 3'

I'm convinced there are better ways to do this and I just haven't found it yet. Thanks in advance.

There's certainly some boolean and/or arithmetic logic to make an expression work that could be placed in the ? , but this will only obfuscate the behaviour.

I would recommend to use indentation to make the logic clear and readable:

const string = a < b ? 'value 1'
             : a > c ? 'value 2'
             : 'value 3';
const string = a < b ? 'value 1' :
               a > c ? 'value 2' :
               'value 3';

While your variant on my opinion is the clearest one, here is another similar way of doing this

 // Set values const a = 4, b = 3, c = 5; // Do inline conditional check const string = a<b &&'value 1' || a>c &&'value 2' || 'value 3'; // Log console.log(string)

Unless your are the only person keeping this code why not go to the most readable way despite the number of lines?

const string = 'value3'

if( a < b ) string = 'value1'
else if( a > c ) string = 'value2'

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