2012-09-04 32 views
-6

你怎麼在Javascript中編寫OR如何在Javascript中編寫OR?

例子:

if (age **or** name == null){ 
    do something 
} 
+0

什麼語言可以讓你做'(年齡或名字== NULL)'? –

+6

StackOverflow不是學習語言的基本語法的好地方。試試參考書或網站。 –

+0

@Quentin我的壞我剛纔注意到它 –

回答

15

只需使用:

if (age == null || name == null){  
    // do something  
} 

儘管如此,如果你只是在測試,看看是否有變量的值(因此是「falsey」,而不是等於null),你可以改用:

if (!age || !name){  
    // do something  
} 

參考文獻:

10
if (age == null || name == null) { 

} 

注意:您可能想看看這個線程,Why is null an object and what's the difference between null and undefined?,用於在JS空/未定義變量的信息。

+0

'==='會更好一點smtge –

+0

不要只檢查一個空變量,它也可能是未定義的。見http://stackoverflow.com/questions/2559318/how-to-check-for-undefined-or-null-variable-in-javascript – pdjota

+0

@pdjota'undefined == null'爲true;你只需要區分是否使用'==='或特別關心差異。 –

0

您遇到的問題是關聯的方式。 (age or name == null)實際上是((age or name) == null),這不是你想說的。你想要((age == null) or (name == null))。如有疑問,請插入圓括號。如果你把括號括起來並進行評估,你會發現情況變得像(true == null)(false == null)

-1

我們沒有OR運營商在JavaScript中,我們使用||相反,你的情況做:

if (age || name == null) { 
    //do something 
} 
相關問題