JavaScript變量類型的判斷

JavaScript變量類型的判斷

JavaScript中有許多判斷變量類型的方法,這裏我將介紹他們的用法和區別

先定義一些變量:

var a = 123;
var b = “red”;
var c = true;
var d = [1,2,3];
var e = {name:123};
var f = function(){alert(“123”)};
var g = null;
var h = undefined;
var i = date;
var j = /at/g;
var k = Error;

1.typeof

alert(typeof a);//number
alert(typeof b);//string
alert(typeof c);//boolean
alert(typeof d);//object
alert(typeof e);//object
alert(typeof f);//function
alert(typeof g);//object
alert(typeof h);//undefine
alert(typeof i);//object
alert(typeof j);//object
alert(typeof k());//object
優點:使用簡單,直接輸出結果
缺點:可檢測類型太少,無法檢測object對象的類型

2.instanceof

alert(a instanceof Number);//false
alert(b instanceof String);//false
alert(c instanceof Boolean);//false
alert(d instanceof Array);//true
alert(e instanceof Object);//true
alert(f instanceof Function);//true
alert(g instanceof Object);//false
alert(h instanceof Object);//false
alert(i instanceof Date);//true
alert(j instanceof RegExp);//true
alert(k() instanceof Error);//true
優點:能檢測出複雜類型
缺點:基本類型無法檢測

3.constructor

alert(a.construtor);//Number
alert(b.construtor);//String
alert(c.construtor);//Boolean
alert(d.construtor);//Array
alert(e.construtor);//Object
alert(f.construtor);//Fuction
alert(g.construtor);//g不存在constructor
alert(h.construtor);//h不存在constructor
alert(i.construtor);//Date
alert(j.construtor);//RegExp
alert(k.construtor);//Error
優點:能檢測出大部分類型
缺點:constructor可以被修改

4.Object.prototype.toString.call()

alert(Object.prototype.toString.call(a));//[object Number]
alert(Object.prototype.toString.call(b));//[object String]
alert(Object.prototype.toString.call(c));//[object Boolean]
alert(Object.prototype.toString.call(d));//[object Array]
alert(Object.prototype.toString.call(e));//[object Object]
alert(Object.prototype.toString.call(f));//[object Function]
alert(Object.prototype.toString.call(g));//[object Null]
alert(Object.prototype.toString.call(h));//[object Undefined]
alert(Object.prototype.toString.call(i));//[object Date]
alert(Object.prototype.toString.call(j));//[object RegExp]
alert(Object.prototype.toString.call(k()));//[object Error]
可以檢測所有類型但在IE6之下undefined null均爲object

這時就會有人說Object.prototype.toString.call()太長,那麼jquery中封裝了一種方法$.type和Object.prototype.toString.call()原理相同

通常情況下typeof就足夠了,遇到object類型可以選用instanceof或者constructor方法,如果還不行就使用最後一種方法

以下是我自己寫的一個方法來判斷數據類型

    var a = [123,"123",true,{num:1},function b(){},null,undefined,Date,/at/g,Error];
    function judgeType() {
        var Type = new String();
        for(var i in arguments){
            Type[i] = "";//初始化數組b[i];
           Type[i] = Object.prototype.toString.call(arguments[i]).slice(8,-1);//將數據類型按照順序添加入數組Type
        }
        return Type;//將類型數組返回
    }
    var type = judgeType(123,"123",true,{num:1},function b(){},null,undefined,new Date(),/at/g,new Error());//調用數組,數組參數可以爲多個
    console.log(type);//在控制檯打印數據類型
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章