Program JavaScript do sprawdzania, czy zmienna jest niezdefiniowana lub zerowa

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 nullwith ==sprawdza zarówno wartości, jak nulli undefined. Dzieje się tak, ponieważ null == undefinedwartoś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

typeofOperator undefinedwartość powróci niezdefiniowane. Dlatego możesz sprawdzić undefinedwartość za pomocą typeofoperatora. Ponadto nullwartości są sprawdzane za pomocą ===operatora.

Uwaga : nie możemy użyć typeofoperatora for, nullponieważ zwraca obiekt.

Interesujące artykuły...