JavaScript之类型检测

博客介绍了JavaScript中几种数据类型检测方法。typeof可检测基本数据类型,但检测null有历史问题,检测复杂引用类型都返回object;instanceof基于原型链查找,返回布尔值;Object.peototype.toString.call()调用Object原型方法;constructor指向构造函数;还提到了duck type概念。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、typeof

typeof undefined;    //undefined
typeof true;         //boolean
typeof 1;            //number
typeof NaN;          //number
typeof function(){}; //function
typeof new Object(); //object
typeof '';           //string
typeof [1,2];        //object
typeof null;         //object
typeof new Number(1);//object

typeof能检测出基本数据类型

由于历史原因typeof null结果为object

在检测对象为一个复杂引用类型,例如数组和正则的时候,结果返回为object。

2、instance of

[] instanceof Array;    //true
[] instanceof Object;   //true
new Object() instanceof Array    //false

instance of返回值为一个布尔值

instanceof 是基于原型链进行查找

只要对象的原型链存在待检测类型,都返回true.

3、Object.peototype.toString.call()
 

Object.prototype.toString.call(1);             //[object Number]

Object.prototype.toString.call(new Number(1)); //[object Number]

Object.prototype.toString.call('');             //[object String]

Object.prototype.toString.call(true);            //[object Boolean]

Object.prototype.toString.call(null);            //[object Null] *IE 6,7,8会返回[object Object]

Object.prototype.toString.call(undefined);     //[object Undefined]

Object.prototype.toString.call([]);             //[object Array]

Object.prototype.toString.call({});             //[object Object]

Object.prototype.toString.call(/^$/);            //[object RegExp]

Object.prototype.toString.call((function () {}));//[object Function]

Object.peototype.toString.call()方法是调用Object上的toString原型方法,并将this绑定到待检测对象。

4.constructor


[].constructor===Array; //true
[].constructor===Object; //false

constructor方法会指向待检测对象的构造函数。

5.duck type

当看到一只鸟走起来像鸭子、游泳起来像鸭子、叫起来也像鸭子,那么这只鸟就可以被称为鸭子

外链:https://slartbartfast.cn/articlePage.php?articleid=256

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值