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
998 views
in Technique[技术] by (71.8m points)

不使用三元运算符和 if ,如何优雅地切换变量的值?

RT,维护一个老项目,经常看到这种垃圾代码,有没有比三元运算更优雅的实现呢

// 比如说变量a有1和2两个值,当它初始为1则赋值2,初始为2则赋值1
let a = 1

// 垃圾1
if (a == 1) {
  a = 2
} else {
  a = 1
}

// 优雅1
a = a == 1 ? 2 : 1

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

1 Answer

0 votes
by (71.8m points)

如果值均为数字 一个非常优雅的写法 可以这样

    // 初始值
    a = val1;
    
    a = (val1 + val2) - a;
   
    // 为了防止 val1 + val2溢出可以这样
    a = (val1 ^ val2) ^ a;

    // 简洁的写法 
    a ^= val1 ^ val2; // 上面已经有人给出这个答案了

效果
image.png


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

...