判断基本数据类型和引用数据类型

基本数据类型 string number boolean undefined null
typeof 返回值string number boolean undefined function object
typeof 不能区分object array null,返回值都是object

可以用 obj instanceof Object 返回true则为对象
            [1,2] instanceof Array 返回true则为数组
            new Date() instanceof Date 返回true则为日期对象
instanceof 判断左边操作数的原型链上是否有右边构造函数的prototype属性*/

也可以用   Object.prototype.toString.apply(x)
var   gettype=Object.prototype.toString
gettype.call('aaaa')        输出      [object String]
gettype.call(2222)         输出      [object Number]
gettype.call(true)          输出      [object Boolean]
gettype.call(undefined)  输出      [object Undefined]
gettype.call(null)                  输出   [object Null]
gettype.call({})                   输出   [object Object]
gettype.call([])                    输出   [object Array]
gettype.call(function(){})     输出   [object Function]


封装为一个函数fun(),可以判断基本数据类型和引用数据类型:

function fun(x){
    if(typeof (x)=="object"){
        if(Object.prototype.toString.apply(x)==="[object Array]"){
            return Array;
        }
        if(Object.prototype.toString.apply(x)==="[object Date]"){
            return Date;
        }
        if(Object.prototype.toString.apply(x)==="[object Null]"){
            return null;
        }
        if(Object.prototype.toString.apply(x)==="[object Object]"){
            return Object;
        }
    }else{
        return typeof(x)
    }
}
var a=function(){};
console.log(fun(a));

 

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值