假设有任意变量,定义如下:
var a = function() {/* Statements */};
我想要一个函数来检查变量的类型是否为类函数。例如:
function foo(v) {if (v is function type?) {/* do something */}};
foo(a);
我怎样才能检查变量a是否为上述定义的函数类型?
假设有任意变量,定义如下:
var a = function() {/* Statements */};
我想要一个函数来检查变量的类型是否为类函数。例如:
function foo(v) {if (v is function type?) {/* do something */}};
foo(a);
我怎样才能检查变量a是否为上述定义的函数类型?
当前回答
if (typeof v === 'function') {
// do something
}
其他回答
如果你使用Lodash,你可以用_.isFunction来实现。
_.isFunction(function(){});
// => true
_.isFunction(/abc/);
// => false
_.isFunction(true);
// => false
_.isFunction(null);
// => false
如果value是一个函数,该方法返回true,否则返回false。
Const foo = function() {}; If (typeof foo === 'function') { console.log(“函数”) }
另一种简单的方法:
var fn = function () {}
if (fn.constructor === Function) {
// true
} else {
// false
}
if (typeof v === 'function') {
// do something
}
注意这一点:
typeof Object === "function" // true.
typeof Array === "function" // true