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 null
együtt ==
ellenőrzi mind null
és undefined
értékeket. Ez azért van, mert null == undefined
igaznak é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 typeof
operátora meghatározatlanul undefined
tér vissza. Ezért undefined
az typeof
operá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 typeof
operátort nem használhatjuk , null
mert az objektumot ad vissza.