示例 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()
方法返回一个指定对象类型的字符串。
另请阅读