変数が関数型であるかどうかをチェックするJavaScriptプログラム

Javascript

例1:instanceof演算子の使用

// program to check if a variable is of function type

function testVariable(variable) {
      
    if(variable instanceof Function) {
        console.log('The variable is of function type');
    }
    else {
        console.log('The variable is not of function type');
    }
}

const count = true;
const x = function() {
    console.log('hello')
};

testVariable(count);
testVariable(x);

出力

The variable is not of function type
The variable is of function type

上記のプログラムでは、 instanceof 演算子は、変数のタイプをチェックするために使用されます。


例2:typeof演算子の使用

// program to check if a variable is of function type

function testVariable(variable) {
      
    if(typeof variable === 'function') {
        console.log('The variable is of function type');
    }
    else {
        console.log('The variable is not of function type');
    }
}

const count = true;
const x = function() {
    console.log('hello')
};

testVariable(count);
testVariable(x);

出力

The variable is not of function type
The variable is of function type

上記のプログラムでは、 typeof 演算子は厳密に等しいで使用されます === 変数のタイプをチェックする演算子。

ザ・ typeof 演算子は変数のデータ型を指定します。 === 変数が値とデータ型の点で等しいかどうかをチェックします。


例3:Object.prototype.toString.call()メソッドの使用

// program to check if a variable is of function type

function testVariable(variable) {
      
    if(Object.prototype.toString.call(variable) == '[object Function]') {
        console.log('The variable is of function type');
    }
    else {
        console.log('The variable is not of function type');
    }
}

const count = true;
const x = function() {
    console.log('hello')
};

testVariable(count);
testVariable(x);

出力

The variable is not of function type
The variable is of function type

ザ・ Object.prototype.toString.call() メソッドは、オブジェクトタイプを指定する文字列を返します。



Hope this helps!

Source link

コメントを残す

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