Ebben a példában megtanul olyan JavaScript programot írni, amely ellenőrzi, hogy egy változó nincs-e definiálva vagy null.
A példa megértéséhez ismernie kell a következő JavaScript programozási témákat:
- A JavaScript null és undefined
- Operator JavaScript típusa
- JavaScript Function és Function Expressions
1. példa: Ellenőrizze, hogy nem definiált vagy 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);
Kimenet
A változó nem undefined és null A változó sem undefined, sem null A változó undefined vagy null A változó undefined vagy null
A fenti programban egy változó ellenőrzése megtörtént, ha egyenértékű a null. Az nullegyütt ==ellenőrzi mind nullés undefinedértékeket. Ez azért van, mert null == undefinedigaznak értékeli.
A következő kód:
if(variable == null) (… )
egyenértékű
if (variable === undefined || variable === null) (… )
2. példa: a typeof használata
// 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);
Kimenet
A változó nem undefined és null A változó sem undefined, sem null A változó undefined vagy null A változó undefined vagy null
Az érték typeofoperátora meghatározatlanul undefinedtér vissza. Ezért undefinedaz typeofoperátor segítségével ellenőrizheti az értéket . Az nullértékeket az ===operátor segítségével is ellenőrizzük .
Megjegyzés : Az typeofoperátort nem használhatjuk , nullmert az objektumot ad vissza.








