js中判断对象具体类型

大家可能知道js中判断对象类型可以用typeof来判断。看下面的情况

<script>
    alert(typeof 1);//number
    alert(typeof "2");//string
    alert(typeof [1,2,3]);//object
    alert(typeof {"name":"zhuhui"})//object
</script>

  从上面中我们可以看出数组和普通对象用typeof判断出来都是object,但是现在我们有这个需求,我们要明确判断出这个对象是具体的哪个对象(比如数组对象,日期对象,正则表达式对象,其他自定义对象,DOM对象等等)那怎么办呢。其实js中有个方法可以准备的判断出

Object.prototype.toString.call

  

var type=function(v){
      		return Object.prototype.toString.call(v);
        };
        alert(type(null));//[object Null]
        alert(type(undefined));//[object Undefined]
        alert(type(1));//[object Number]
        alert(type(true));//[object Boolean]
        alert(type("2"));//[object String]
        alert(type([1,2,3]));//[object Array]
        alert(type({"name":"zhuhui"}));//[object Object]
        alert(type(type));//[object Function]
        alert(type(new Date()));//[object Date]
        alert(type(/^d+$/));//[object Regexp]