JS 数据类型检测及限制

本文深入探讨JavaScript中不同类型检测的方法,包括typeof、instanceof及Object.prototype.toString.call等,对比它们的特点与适用场景,帮助开发者更准确地进行类型判断。

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

typeof

typeof("xxx") //"string"
typeof(123)   //"number"
typeof(true)  //"boolean"
typeof(null)  //"object"
typeof(undefined)  //undefined
typeof({name:'xxx'}) //"object"

typeof(function(){}) //"function"
typeof([1,2,3]) //"object"
typeof(new Date())//"object"

typeof总结:

  • 可以识别标准类型(null除外)
  • 不能识别具体的对象类型(Function除外)

instanceof

用于检测构造函数的prototype属性是否存在某个实例的原型链上。

[]  instanceof Array;  //true
var a=function(){}
var b=new a();
b instanceof a; //true
        
123 instanceof Number;  //false
"xxx" instanceof String; //false

instanceof总结:

  • 可以识别内置对象,自定义对象
  • 不可识别基本数据类型
  • 必须同一个作用域,如果存在多个作用域,比如多个frame,判断不出。

Object.prototype.toString.call 

Object.prototype.toString.call([]); //"[object Array]"
Object.prototype.toString.call({}); //"[object Object]"
Object.prototype.toString.call(function(){}) //"[object Function]"
Object.prototype.toString.call("123") //"[object String]"
Object.prototype.toString.call(new Date)//"[object Date]"
var a=function(){}
Object.prototype.toString.call(new a)//"[object Object]"

总结:

  • 可以判断标准类型和内置对象类型
  • 不能识别自定义对象类型

contructor属性

"xxx".constructor===String //true
(1).constructor===Number //true
(true).constructor===Boolean//true
({}).constructor===Object //true
new Date().constructor===Date//true
([]).constructor===Array //true
var a=function(){}
var b=new a();
b.constructor===a; //true

总结:

  • 可以判断内置对象类型(undefined和null除外,因为undefined和null没有构造函数)
  • 可以判断普通对象类型
  • 可以判断自定义对象类型

End

  以上是目前,我所了解的,仅供大家参考,如有错误,还望指出,如有补充,还望指点,thank you!!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值