Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/391.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
检查变量类型JavaScript最准确的方法是什么?_Javascript_Variables_Typechecking - Fatal编程技术网

检查变量类型JavaScript最准确的方法是什么?

检查变量类型JavaScript最准确的方法是什么?,javascript,variables,typechecking,Javascript,Variables,Typechecking,我需要检查JavaScript中变量的类型。我知道三种方法: instanceof运算符:if(instanceof函数) 运算符类型:if(类型a==“函数” toString方法(jQuery使用此方法):Object.prototype.toString.call(a)==“对象函数”” 在这些解决方案之间进行类型检查的最准确方法是什么?为什么?请不要告诉我上一个解决方案更好,因为jQuery使用了它。我的自制函数如何确定变量“类型”?它还可以确定自定义对象的类型: function wh

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

  • instanceof运算符:
    if(instanceof函数)

  • 运算符类型:
    if(类型a==“函数”

  • toString方法(jQuery使用此方法):
    Object.prototype.toString.call(a)==“对象函数””


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

    我的自制函数如何确定变量“类型”?它还可以确定自定义对象的类型:

    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
    

    我不是在寻找差异,我知道它们的行为。我想知道它们之间最安全的解决方案是什么?为什么?你的意思是准确吗?cletus链接的线程回答了你的准确度问题。但最后一个解决方案在我测试时没有提到(A级浏览器):是的。