[JavaScript]変数が関数タイプであるかどうかをチェックする

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

Source

コメントを残す

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