条件(三元)运算符

2018-02-23大约4分钟

对于一些简单的条件赋值语句,ifswitch都显得有点笨重,这时候,可以尝试一下用?:这个三元条件运算符。

用法

?:运算符是JavaScript中唯一的一个三元运算符,顾名思义,就是使用三个操作数。这个运算符通常被用作if..else语句的快捷用法。先看个例子:

const number = 10;
const negative = number < 0 ? true : false; 
console.log(negative);

例子中,?:运算符的?前面是个表达式,其实也可以是个变量,如果判定条件为true,则返回:前的表达式,反之则返回:之后的表达式。

看更多的例子:

console.log(undefined ? true : false);
console.log(null ? "yes" : "no");

编码风格探讨(1)

在看别人写的代码的时候,也许会发现类似这样的语句:

const number = 10;
let negative;
number < 0 ? negative = true : negative = false;  // 注意这一行
console.log(negative);

你会发现上面的代码是管用的,那么这种风格好吗?

你选择哪种风格, "const negative = number < 0 ? true : false; " 还是 "number < 0 ? negative = true : negative = false;"
第一个选项,明确利用的是?后面表达式后面的返回值,这也是?:运算符的本意;
第二个选项,隐含地使用了?后面表达式支持赋值语句,因此也不再在乎返回值。
对于这种情况,我个人比较倾向于选择第一种用法,代码更易阅读。

编码风格探讨(2)

有时候呢,还会发现一些更奇特的代码:

案例一

const firstCheck = false;
const secondCheck = false;
const thirdCheck = true;
const access = firstCheck ? 'Access granted' : secondCheck ? 'Access granted' : thirdCheck ?  'Access granted': 'Access denied';
  
console.log(access); 

上面的第四行代码容易读吗?

改进的话,这样子会不会更清晰呢?

const firstCheck = false;
const secondCheck = false;
const thirdCheck = true;
let access = "Access denied";
if (firstCheck || secondCheck || thirdCheck) {
    access = "Access granted";
}

console.log(access); 

案例二

const score = 79;
const grade = score >= 95 ? "A" : score >= 85 ? "B" : score >= 75? "C" : "D";
console.log(grade);

第二行代码是不是很难读啊?

改一下,还用最简单的if语句:

const score = 79;
let grade;
if (score >= 95) {
    grade = "A";
} else if (score >= 85) {
    grade = "B";
} else if (score >= 75) {
    grade = "C";
} else {
    grade = "D";
}
console.log(grade);

这么改,虽然代码变长了,可是代码更易读了。

能用?:的地方,一定要用?:运算符吗?
用?:代码行数最少,短小精悍。但是行数最少的不一定是最易懂的,要根据情况来决定是否使用。如果只是为了代码精简,但是写出来的代码晦涩难懂,后续过段时间说不定自己都看不懂