简体   繁体   中英

Combine two values with ternary operator in Javascript

Having the following code snippet:

const value1 = isSomething ? 'a' : isSomethingElse ? 'b' : 'c';
const value2 = isSomething ? 1 : isSomethingElse ? 2 : 3;

Those two variables are depending of the same other variables behavior ( isSomething and isSomethingElse )

Is there a way to write this code into a single line?

You can use arrays, and destructuring assignment, but it will not be faster:

const [value1, value2] = isSomething ? ['a', 1] 
                       : isSomethingElse ? ['b', 2] : ['c', 3];

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