检查变量类型JavaScript的最准确方法是哪种?

时间:2010-05-12 08:02:08

标签: javascript variables typechecking

我需要检查JavaScript中变量的类型。我知道3种方法:

  1. instanceof operator:if(a instanceof Function)

  2. typeof运算符:if(typeof a=="function"

  3. toString方法(jQuery使用此方法):Object.prototype.toString.call(a) == "[object Function]"

  4. 在这些解决方案之间进行类型检查的最准确方法是什么?为什么?请不要告诉我最后一个解决方案更好,只是因为jQuery使用它。

1 个答案:

答案 0 :(得分:1)

我的家酿啤酒功能如何确定变量'type'?它还可以确定自定义对象的类型:

function whatType(somevar){
    return String(somevar.constructor)
            .split(/\({1}/)[0]
            .replace(/^\n/,'').substr(9);
}
var num = 43
    ,str = 'some string'
    ,obj = {}
    ,bool = false
    ,customObj = new (function SomeObj(){return true;})();

alert(whatType(num)); //=>Number
alert(whatType(str)); //=>String
alert(whatType(obj)); //=>Object
alert(whatType(bool)); //=>Boolean
alert(whatType(customObj)); //=>SomeObj

基于变量的构造函数属性,您也可以这样做:

function isType(variable,type){
 if ((typeof variable).match(/undefined|null/i) || 
       (type === Number && isNaN(variable)) ){
        return variable
  }
  return variable.constructor === type;
}
/** 
 * note: if 'variable' is null, undefined or NaN, isType returns 
 * the variable (so: null, undefined or NaN)
 */

alert(isType(num,Number); //=>true

现在alert(isType(customObj,SomeObj)返回false。但是如果SomeObj是一个普通的构造函数,它返回true。

function SomeObj(){return true};
var customObj = new SomeObj;
alert(isType(customObj,SomeObj); //=>true