我正在嘗試撰寫一個簡單的腳本來查看信用號碼評級并顯示相應的文本評級。當我到達第二個 else/if 陳述句時 if-else 陳述句中斷,我無法弄清楚為什么超過 601 的任何東西都只是讀取“POOR”。
credit = 690;
if (credit <= 600) {
document.write("VERY POOR");
}
else if (credit >= 601 || credit <= 657){
document.write("POOR");
}
else if (credit >= 658 || credit <= 719){
document.write("FAIR");
}
else if (credit >= 720 || credit <= 780){
document.write("GOOD");
}
else {
(credit >= 781 || credit <= 850);
document.write("EXCELLENT");
}
uj5u.com熱心網友回復:
您應該將 替換||為&&。
|| 表示 OR,同時 && 表示 AND。您需要檢查信用是否大于 601 且小于 657。
試試這個方法:
credit = 690;
if (credit <= 600) {
document.write("VERY POOR");
}
else if (credit >= 601 && credit <= 657){
document.write("POOR");
}
else if (credit >= 658 && credit <= 719){
document.write("FAIR");
}
else if (credit >= 720 && credit <= 780){
document.write("GOOD");
}
else {
(credit >= 781 && credit <= 850);
document.write("EXCELLENT");
}
uj5u.com熱心網友回復:
您的代碼的問題在于,當您撰寫代碼時:
else if (credit >= 601 || credit <= 657){
document.write("POOR");
}
這是真的,所以它會說 POOR,因為你正在處理 or 子句女巫意味著(真或假)=(假或真)=真:
解決方案是洗掉第一個引數:
let credit = 690;
if(credit <= 600) {
console.log(credit)
document.write("VERY POOR");
}
else if (credit <= 657){
console.log(credit)
document.write("POOR");
}
else if (credit <= 719){
console.log(credit)
document.write("FAIR");
}
else if (credit <= 780){
console.log(credit)
document.write("GOOD");
}
else {
(credit <= 850);
console.log(credit)
document.write("EXCELLENT");
}
ps:代碼將無法完美運行,您需要在兩個值之間放置'and'子句(&&)
uj5u.com熱心網友回復:
在這些情況下,您必須使用 &&
&& 運算子會定義兩個值都必須為真,OR 運算子會定義要執行,只有一個值為真。
你可以在這里閱讀更多: https ://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_AND
let credit = 750;
if (credit <= 600) {
document.write("VERY POOR");
}
else if (credit >= 601 && credit <= 657){
document.write("POOR");
}
else if (credit >= 658 && credit <= 719){
document.write("FAIR");
}
else if (credit >= 720 && credit <= 780){
document.write("GOOD");
}
else {
(credit >= 781 && credit <= 850);
document.write("EXCELLENT");
}
uj5u.com熱心網友回復:
看來您混淆了 AND 和 OR 布爾條件,您的條件:
else if (credit >= 601 || credit <= 657){
document.write("POOR");
}
捕獲所有優于 601 的內容,因為這實際上是您要求它執行的操作。如果你想要一個范圍檢查,你應該寫:
else if (credit >= 601 && credit <= 657){
document.write("POOR");
}
對于你們每個人的 else if 陳述句,依此類推。:)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/454870.html
標籤:javascript if 语句
