Ternary Operator(三元運算子) | 歷史共業
文章推薦指數: 80 %
Ternary Operator(三元運算子) - Ronnie Chang.
TernaryOperator(三元運算子)2017-04-09前端筆記JavaScript如果if-else內的處理邏輯很簡單具有共同性,例如只是宣告或回傳某值,可以考慮使用TernaryOperator(三元運算子)寫成,不用長長一串之外更為直觀,這是自己常寫ifelse被制約而忘掉的寫法:P。
例如:
1234vargrade=function(score){if(score<60){return'failed'}else{return'passed'}}
用TernaryOperator寫成:
123vargrade=function(score){returnscore<60?'failed':'passed';};
一行解決,如果支援ES6的話搭配Arrowfunction使用,更乾淨俐落。
1constgrade=(score)=>score<60?'failed':'passed';//availablewithES6
可以多組判斷串接,相當於if之後的elseif:
12constrank=(score)=>score>=95?'S':score>=80?'A':'B';console.log(rank(95),rank(85),rank(70));//"S""A""B"
直接寫在變數宣告中,應用上能限制一些意外的計算結果如NaN或Infinity。
12345678functionhitRate(hit,shot){//varrate=hit/shot;/*當shot=0,hit=0時會得到NaN*/varrate=shot==0?0:hit/shot;//限制shot為0時讓rate直接代0if(rate>0.4){console.log('MVP');}elseif...}
延伸文章資訊
- 1?: operator - C# reference | Microsoft Docs
Learn about the C# ternary conditional operator that returns the result of one of the two express...
- 2Ternary Operator(三元運算子) | 歷史共業
Ternary Operator(三元運算子) - Ronnie Chang.
- 3What is a Ternary Operator? - Computer Hope
The ternary operator is an operator that exists in some programming languages, which takes three ...
- 4Make Your Code Cleaner with JavaScript Ternary Operator
Introduction to JavaScript ternary operator ... In this syntax, the condition is an expression th...
- 5JavaScript Ternary Operator (with Examples) - Programiz
What is a Ternary operator? ... A ternary operator evaluates a condition and executes a block of ...