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);//在控制台打印数据类型

猜你喜欢

转载自blog.csdn.net/qq_39159168/article/details/78294508