Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
108 views
in Technique[技术] by (71.8m points)

Having a 1 line conditional update other variables in Javascript

Not sure if this is possible but is there a way this can be simplified to one line without using an if else call? i.e update all variables when a certain condition is met?

const dogStatus = present ? "bark" : "beep";
const catStatus = present ? "meow" : "meep";
const fishStatus = present ? "blub" : "bleeboop";
question from:https://stackoverflow.com/questions/66051581/having-a-1-line-conditional-update-other-variables-in-javascript

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The conditional operator and destructuring can do this:

const [dogStatus, catStatus, fishStatus] = present ? ['bark', 'meow', 'blub'] : ['beep', 'meep', 'bleeboop'];

For the sake of code organization, I'd strongly consider if having just a single variable instead of multiple standalone variables would be possible, I'd prefer it in most situations:

const status = present
  ? { dog: 'bark', cat: 'meow', fish: 'blub' }
  : { dog: 'beep', cat: 'meep', fish: 'bleeboop' };

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...