JavaScript 程序:检查变量是否为函数类型
要理解这个示例,你应该具备以下 JavaScript 编程主题的知识:
示例 1:使用 instanceof 运算符
// 程序用于检查变量是否为函数类型
function testVariable(variable) {
if (variable instanceof Function) {
console.log("该变量是函数类型");
} else {
console.log("该变量不是函数类型");
}
}
const count = true;
const x = function () {
console.log("hello");
};
testVariable(count);
testVariable(x);
输出
该变量不是函数类型
该变量是函数类型
在上述程序中,使用了 instanceof
运算符来检查变量的类型。
示例 2:使用 typeof 运算符
// 程序用于检查变量是否为函数类型
function testVariable(variable) {
if (typeof variable === "function") {
console.log("该变量是函数类型");
} else {
console.log("该变量不是函数类型");
}
}
const count = true;
const x = function () {
console.log("hello");
};
testVariable(count);
testVariable(x);