我對問號和三元??上的冒號感到困惑,有人可以解釋如何正確地做到這一點
const bill = 220;
const fifty = 50;
const oneHundred = 100;
const twoHundred = 200;
if(bill < fifty)
console.log(`(A) bill is less than 50`);
else if(bill < oneHundred)
console.log('(B) bill is greater than 50');
else if(bill < twoHundred)
console.log('(C) bill is greater than 100');
else if(bill > twoHundred)
console.log('(D) bill is greater than 200');
uj5u.com熱心網友回復:
條件(三元)運算子
條件(三元)運算子是唯一一個接受三個運算元的 JavaScript 運算子:一個條件后跟一個問號 (?),然后是一個如果條件為真則執行的運算式,后跟一個冒號 (:),最后是運算式如果條件不成立則執行。此運算子經常用作 if...else 陳述句的替代方法。
const bill = 220;
const fifty = 50;
const oneHundred = 100;
const twoHundred = 200;
console.log(
bill < fifty
? "(A) bill is less than 50"
: bill < oneHundred
? "(B) bill is greater than 50"
: bill < twoHundred
? "(C) bill is greater than 100"
: "(D) bill is greater than 200"
);
uj5u.com熱心網友回復:
您可以從三元運算子獲得訊息。
為了更好地閱讀(和理解)運算式是嵌套的級別。
const
bill = 220,
fifty = 50,
oneHundred = 100,
twoHundred = 200,
message = bill < fifty
? '(A) bill is less than 50'
: bill < oneHundred
? '(B) bill is greater than 50'
: bill < twoHundred
? '(C) bill is greater than 100'
: bill > twoHundred
? '(D) bill is greater than 200'
: '';
console.log(message);
uj5u.com熱心網友回復:
簡單的解釋方法見此表格
condition ? (if condition == true) : (if condition == false)
您現在需要做的另一件事是根據條件“回傳”資料
let age = 30
let message = age > 18 ? "Can pass" : "Can't pass"
console.log(message) // Output: Can pass
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/468974.html
標籤:javascript if 语句 条件运算符
上一篇:我可以在if陳述句中初始化不同型別的物件嗎?[復制]
下一篇:根據另一列中的值獲取每列的平均值