js中判断数据类型方法

js中有7种数据类型,其中

三种基本类型:Number、String、Boolean
两种引用类型:Object、Array
两种特殊类型:undefined、null

  • 1.判断boolean类型的不再多说,我们都知道undefined、null、NaN、0、’'这几种大都是false,其余都是true
  • 2.typeof,他无法判断数组和对象,返回的都是Object
 console.log(typeof str);//string
 console.log(typeof arr);//object
 console.log(typeof obj);//object
 console.log(typeof num);//number
 console.log(typeof b);//boolean
 console.log(typeof n);//null是一个空的对象
 console.log(typeof u);//undefined
 console.log(typeof fn);//function
  • 3.instanceof ,可以区分数组和对象,但是无法判断String、boolean
// 我们定义了arr是数组,obj是对象的变量
 console.log(obj instanceof Object);// true
 console.log(arr instanceof Array);//  true
 console.log(obj instanceof Array);//  false
  • 4.constructor也能判断是数组还是对象
console.log(obj.constructor == Object);//true
console.log(arr.constructor == Array);//true
  • 5.利用tostring()方法,这个方法是最佳的方案,可判断对象、数组、布尔、字符串
// arr、obj、fn分别是我提前定义的数组、对象、函数
console.log(Object.prototype.toString.call(arr));//[object Array],结果是字符串
console.log(Object.prototype.toString.call(obj));//[Object Object]
console.log(Object.prototype.toString.call(fn));//[Object Function]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值