这段if可以还有优化的余地吗吗?
if (this.switchNum == 1) {
this.switchNum = 2
} else {
this.switchNum = 1
}
这段if可以还有优化的余地吗吗?
if (this.switchNum == 1) {
this.switchNum = 2
} else {
this.switchNum = 1
}
// 原代码
if (this.switchNum == 1) {
this.switchNum = 2
} else {
this.switchNum = 1
}
一般像这种简单的if...else分支语句,我会第一时间考虑三元运算符
下的方法。
改造如下:
this.switchNum = this.switchNum == 1 ? 2 : 1
可以分开解析:
// 赋值符“=”后边这段代码如下
this.switchNum == 1 ? 2 : 1
其中?
之前的是条件,也就是判断this.switchNum是否与1相等:
前边代表前边结果成立
返回的值:
后边代表前边结果不成立
返回的值
所以这段代码(this.switchNum == 1 ? 2 : 1
)要么返回2,要么返回1,完全取决于this.switchNum == 1
还是this.switchNum != 1
那么既然值得到了,就赋值给this.switchNum
即可
最终的结果就是上边写的:
this.switchNum = this.switchNum == 1 ? 2 : 1
10 回答11.1k 阅读
6 回答3k 阅读
5 回答4.8k 阅读✓ 已解决
4 回答3.1k 阅读✓ 已解决
2 回答2.6k 阅读✓ 已解决
3 回答5.1k 阅读✓ 已解决
3 回答1.8k 阅读✓ 已解决
用三元运算符也可以
this.switchNum = this.switchNum == 1 ? 2 : 1;