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

Categories

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.1k views
Welcome To Ask or Share your Answers For Others

1 Answer

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

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

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

效果
image.png


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...