作为一个后端开发人员,有时候想写点前端代码时,面对js中的一些未知的写法也是很苦恼的,想借鉴却连代码都看不懂,例如今日份的JS三元表达式,下面来一起学习下吧^-^!
1、JS三元运算符是什么?
条件(三元)运算符是 JavaScript 仅有的使用三个操作数的运算符。一个条件后面会跟一个问号(?),如果条件为 truthy ,则问号后面的表达式A将会执行;表达式A后面跟着一个冒号(:),如果条件为 falsy ,则冒号后面的表达式B将会执行。本运算符经常作为 if
语句的简捷形式来使用。
小例子:
function getFee(isMember) {
return (isMember ? '$2.00' : '$10.00');
}
console.log(getFee(true));
// expected output: "$2.00"
console.log(getFee(false));
// expected output: "$10.00"
console.log(getFee(null));
// expected output: "$10.00"
2、怎么用,标准语法是什么?
语法:
condition ? exprIfTrue : exprIfFalse
参数:
condition:计算结果用作条件的表达式。
exprIfTrue: 如果表达式 condition
的计算结果是 truthy(它和 true
相等或者可以转换成 true
),那么表达式 exprIfTrue
将会被求值。
exprIfFalse:如果表达式 condition
的计算结果是 falsy(它可以转换成 false
),那么表达式 exprIfFalse
将会被执行。
3、简单使用:
例1:
var age = 26;
var beverage = (age >= 21) ? "Beer" : "Juice";
console.log(beverage); // "Beer"
例2:(表达式值为假的情况,除了 false
,可能的假值表达式还有:null
、NaN
、 0
、空字符串( ""
)、和 undefined
)
function greeting(person) {
var name = person ? person.name : "stranger";
return "Howdy, " + name;
}
console.log(greeting({name: 'Alice'})); // "Howdy, Alice"
console.log(greeting(null)); // "Howdy, stranger"
4、条件链:
这个三元操作符是右结合的,也就是说你可以像这样把它链接起来, 和 if … else if … else if … else
链类似:
function example(…) {
return condition1 ? value1
: condition2 ? value2
: condition3 ? value3
: value4;
}
// Equivalent to:
function example(…) {
if (condition1) { return value1; }
else if (condition2) { return value2; }
else if (condition3) { return value3; }
else { return value4; }
}
5:我遇到的没看懂的实例:
看过三元运算后,顿时就明白了next_step_num的值是怎么得来得了。
this.nextStep=function() {
if (curPage>=size) {
return false;
}
var next_step_num = curPage == 0? 2: curPage == size ? size : curPage+1;
return this.goStep(next_step_num);
};
小结:
三元运算理解起来很简单,主要是自己掌握js的知识很少,也不晓得这种写法,虽然简单,不过还是要总结下自己加深印象,希望以后自己这样写。这一句代码顶我这个萌新写一堆if....else...........嘤嘤
参考(知识来源):
!!!对了,不能忘了我的知识来源,本知识点的学习总结源自于:
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/Conditional_Operator