我很確定我在這里遺漏了一些基本的東西,但是我在if 陳述句中使用多個or或||運算子時遇到了麻煩。
出于某種原因,if 陳述句沒有捕獲 name 變數:
testword = "billy"
if ((testword != "billy") ||
(testword != "tom") ||
(testword != "sara") ||
(testword != "michael")) {
console.log("none of the names match")
} else {
console.log("name found!")
}
當我嘗試這個時,我得到了none of the names match我應該得到的name found!
uj5u.com熱心網友回復:
你的邏輯有點復雜
一種更簡單的寫入和理解方法是將所有這些名稱放在一個陣列中,然后查看該陣列是否包含 testword。這只是一個布爾測驗
const testword = "billy",
words = ["billy", "tom", "sara", "michael"]
if (words.includes(testword)) {
console.log("name found!")
} else {
console.log("none of the names match")
}
uj5u.com熱心網友回復:
or當任何條件不等于時,運算子執行為真,testword因此記錄none of the names match
但是,您可以嘗試將代碼更改為
testword = "billy"
names = ['billy','tom','sara','michael',]
if (names.indexOf(testword) != -1) {
console.log("name found!")
} else {
console.log("none of the names match")
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/393486.html
標籤:javascript if 语句
