W tym przykładzie nauczysz się pisać program JavaScript, który sprawdzi, czy zmienna jest niezdefiniowana czy zerowa.
Aby zrozumieć ten przykład, powinieneś znać następujące tematy programowania JavaScript:
- JavaScript ma wartość null i undefined
- Operator JavaScript
- Funkcje i wyrażenia funkcyjne JavaScript
Przykład 1: Zaznacz undefined lub null
// program to check if a variable is undefined or null function checkVariable(variable) ( if(variable == null) ( console.log('The variable is undefined or null'); ) else ( console.log('The variable is neither undefined nor null'); ) ) let newVariable; checkVariable(5); checkVariable('hello'); checkVariable(null); checkVariable(newVariable);
Wynik
Zmienna nie jest ani undefined ani null Zmienna nie jest ani undefined ani null Zmienna jest undefined lub null Zmienna jest undefined lub null
W powyższym programie zmienna jest sprawdzana, czy jest równoważna null
. Funkcja null
with ==
sprawdza zarówno wartości, jak null
i undefined
. Dzieje się tak, ponieważ null == undefined
wartościuje jako prawda.
Poniższy kod:
if(variable == null) (… )
jest równa
if (variable === undefined || variable === null) (… )
Przykład 2: użycie typeof
// program to check if a variable is undefined or null function checkVariable(variable) ( if( typeof variable === 'undefined' || variable === null ) ( console.log('The variable is undefined or null'); ) else ( console.log('The variable is neither undefined nor null'); ) ) let newVariable; checkVariable(5); checkVariable('hello'); checkVariable(null); checkVariable(newVariable);
Wynik
Zmienna nie jest ani undefined ani null Zmienna nie jest ani undefined ani null Zmienna jest undefined lub null Zmienna jest undefined lub null
typeof
Operator undefined
wartość powróci niezdefiniowane. Dlatego możesz sprawdzić undefined
wartość za pomocą typeof
operatora. Ponadto null
wartości są sprawdzane za pomocą ===
operatora.
Uwaga : nie możemy użyć typeof
operatora for, null
ponieważ zwraca obiekt.