Javascript教程
JavaScript基础
JavaScript Objects
JavaScript BOM
JavaScript DOM
JavaScript OOP
JavaScript Cookies
JavaScript事件
JavaScript异常
JavaScript常用

JavaScript 检查变量是否为函数类型的程序

用于检查变量是否为函数类型的 JavaScript 程序

在本例中,您将学习编写一个 JavaScript 程序,该程序将检查变量是否为函数类型。
要理解此示例,您应该了解以下JavaScript 编程主题:
JavaScript typeof 运算符 Javascript 函数调用() Javascript 对象 toString()

示例 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() 方法返回一个指定对象类型的字符串。
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4