おいーす、もりたけです。
フリーコードキャンプを日本語で解説!の第107弾です。
JavaScript Algorithms and Data Structures Certification (300 hours)の中の、
Basic JavaScriptの中の、
Use Multiple Conditional (Ternary) Operators
です。
さっそく見ていきましょう。
まずは本文から。
In the previous challenge, you used a single conditional operator. You can also chain them together to check for multiple conditions.
The following function uses if, else if, and else statements to check multiple conditions: function findGreaterOrEqual(a, b) {if (a === b) {return “a and b are equal”;}else if (a > b) {return “a is greater”;}else {return “b is greater”;}}The above function can be re-written using multiple conditional operators:
function findGreaterOrEqual(a, b) {return (a === b) ? “a and b are equal”: (a > b) ? “a is greater”: “b is greater”;}However, this should be used with care as using multiple conditional operators without proper indentation may make your code hard to read. For example:
function findGreaterOrEqual(a, b) {return (a === b) ? “a and b are equal” : (a > b) ? “a is greater” : “b is greater”;}Use multiple conditional operators in the
checkSign
function to check if a number is positive, negative or zero. The function should return “positive”, “negative” or “zero”.
解説していきます。
今回は三項演算子の連結についてです。
if-else文を連結できるように、三項演算子も連結して複数の条件を指定する事ができます。
例を見てみましょう。
上記のコードをこのように変更できます。
ということで今回は三項演算子で複数の条件を扱う処理を学びました。
正直、if-else文でいいのではないかと思います。
では次回!