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() 方法返回一个指定对象类型的字符串


另请阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战