首页 > Web开发 > 详细

js类型判断

时间:2021-07-19 14:15:24      阅读:7      评论:0      收藏:0      [点我收藏+]

js中的数据类型

基本数据类型: Undefined、Null、Boolean、Number、String、Symbol
引用数据类型:Object

1、typeof

typeof可以识别出基本类型:boolean,number,undefined、string、symbol,也可以识别function

但是不能识别null,会把bull、array、object统一归为object。

2、instanceof

instanceof不能识别出基本的数据类型,null、undefined、boolean、number、string、symbol

可以检测出引用类型,如array、object、function,同时对于使用new声明的类型,话可以检测出多层几曾关系。如objA instanceof A 

instanceof一般用来检测对象类型,以及继承关系。

3、constructor

null、undefined没有constructor方法,因此constructor不能判断undefiend和null

但是他是不安全的,因为constructor的指向是可以改变的

4、Object.prototype.toString.call

此方法可以相对较全的判断js的数据类型。

至于再项目中使用哪个个判断,还是要看使用场景、具体的选择、一般类型可以选择typeof,引用类型可以使用instanceof

5、使用例子

console.log(typeof bool); //boolean
console.log(arr instanceof Array);// true
console.log(obj instanceof Object);// true
console.log(fun instanceof Function);// true
console.log(bool.constructor === Boolean);// true
console.log(Object.prototype.toString.call(bool));//[object Boolean]

 

js类型判断

原文:https://www.cnblogs.com/hyt09/p/15029257.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!