js判断数据类型的几种方式

数据类型,包含这7种: number、boolean、symbol、string、object、undefined、function

1、typeof

  • 不能区分null、[]、{}
typeof "" 				string
typeof 1				number
typeof true				boolean
typeof undefined		undefined
typeof null				object
typeof {}				object
typeof []				object
typeof function(){}		function

2、instanceof

  • instanceof 是用来判断 A 是否为 B 的实例,表达式为:A instanceof B,如果 A 是 B 的实例,则返回 true,否则返回 false。 在这里需要特别注意的是:instanceof 检测的是原型

在这里插入图片描述

"1" instanceof String				false
1 instanceof Number					false
true instanceof Boolean				false
{} instanceof Object				true
[] instanceof Array					true
function(){} instanceof Function	true

3、constructor

  • null 和 undefined 无constructor,无法判断
  • constructor是原型prototype的一个属性,当函数被定义时候,js引擎会为函数添加原型prototype,并且这个prototype中constructor属性指向函数引用, 因此重写prototype会丢失原来的constructor
  • 如果自定义对象,开发者重写prototype之后,原有的constructor会丢失,因此,为了规范开发,在重写对象原型时一般都需要重新给 constructor 赋值,以保证对象实例的类型不被篡改
"".constructor==String

new Number().constructor==Number

true.constructor==Boolean

new Function().constructor==Function

new Date().constructor==Date

new Error().constructor==Error

[].constructor==Array

document.constructor==HTMLDocument

window.constructor==Window

4、Object.prototype.toString.call()

  • toString() 是 Object 的原型方法,调用该方法,默认返回当前对象的 [[Class]] 。这是一个内部属性,其格式为 [object Xxx] ,其中 Xxx 就是对象的类型
  • 对于 Object 对象,直接调用 toString() 就能返回 [object Object] 。而对于其他对象,则需要通过 call / apply 来调用才能返回正确的类型信息
Object.prototype.toString.call('') ;    	 		[object String]
Object.prototype.toString.call(1) ;     			[object Number]
Object.prototype.toString.call(true) ;  	 		[object Boolean]
Object.prototype.toString.call(Symbol()); 	 		[object Symbol]
Object.prototype.toString.call(undefined) ;  		[object Undefined]
Object.prototype.toString.call(null) ;  	 		[object Null]
Object.prototype.toString.call(new Function()) ;	[object Function]
Object.prototype.toString.call(new Date()) ;		[object Date]
Object.prototype.toString.call([]) ; 				[object Array]
Object.prototype.toString.call(new RegExp()) ; 		[object RegExp]
Object.prototype.toString.call(new Error()) ; 		[object Error]
Object.prototype.toString.call(document) ;			[object HTMLDocument]
Object.prototype.toString.call(window) ; 			[object global] window 是全局对象 global 的引用
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

守望黑玫瑰

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值