変数が未定義またはnullかどうかを確認するJavaScriptプログラム

Javascript

例1:未定義または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);

出力

The variable is neither undefined nor null
The variable is neither undefined nor null
The variable is undefined or null
The variable is undefined or null

上記のプログラムでは、変数が同等であるかどうかがチェックされます null。 ザ・ null== 両方をチェックします null そして undefined 値。 それの訳は null == undefined に評価します true

次のコード:

if(variable == null) { ... }

と同等です

if (variable === undefined || variable === null) { ... }

例2: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);

出力

The variable is neither undefined nor null
The variable is neither undefined nor null
The variable is undefined or null
The variable is undefined or null

ザ・ typeof の演算子 undefined 値が返される 未定義。 したがって、あなたはチェックすることができます undefined 使用する値 typeof オペレーター。 また、 null 値はを使用してチェックされます === オペレーター。

注意:使用できません typeof の演算子 null それが戻るとき オブジェクト



Hope this helps!

Source link

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です