JS中的数据类型

原始类型

js中的原始类型有:

  • null
  • undefined
  • boolean
  • number
  • string
  • symbol

其中symbol为ES6新增的数据类型

对象类型

除了原始类型,其他的均为对象类型

  • object
  • array
  • function

如何正确判断数据类型

js判断类型的几种方式

  • typeof
  • instanceof
  • constructor
  • Object.prototype.toString.call

typeof 判断类型
对于原始类型:将 null 判断成 object 其他可以正确判断
对于对象类型:正确判断 function 、object 类型,其他均判断成 object

> typeof(null)
< "object"

> typeof(undefined)
< "undefined"

> typeof(false)
< "boolean"

> typeof(1)
< "number"

> typeof('1')
< "string"

> typeof(Symbol())
< "symbol" 
> typeof({1:'a'})
< "object"

> typeof([1,2,3])
< "object"

> typeof(console.log)
< "function"

instanceof 判断类型
instanceof 运算符用于检测构造函数的 prototype 属性是否出现在某个实例对象的原型链上(使用instance判断类型需要特别注意原型链这块)
所以,instanceof 不能判断原始类型,可以正确判断数组、函数、对象类型
可以判断自定义类型

> console.log(null instanceof Object)
< false

> console.log([1,2,3] instanceof Array)
< true

> console.log({1:'a'} instanceof Object)
< true

> var a = function(){return 'a'}
> console.log(a instanceof Function)
< true

构造函数的prototype属性

这里涉及到JS的原型链知识哦,下一篇基础知识里再详细记录。

constructor 判断类型
constructor 是一种用于创建和初始化 class创建的对象的特殊方法。
对于没有构造函数的 null、undefined 不适用

> var a = {1:'a'}
> a.constructor
< ƒ Object() { [native code] }

> var b = [1,2,3]
> b.constructor
< ƒ Array() { [native code] }

> var c = function() {return true}
> c.constructor
< ƒ Function() { [native code] }
> var d = '123'
> d.constructor
< ƒ String() { [native code] }

> var e = 123
> e.constructor
< ƒ Number() { [native code] }

> var f = Symbol(1)
> f.constructor
< ƒ Symbol() { [native code] }

> var g = false
> g.constructor
< ƒ Boolean() { [native code] }

Object.prototype.toString.call 判断类型
利用 Object.prototype 原生的 toString 方法均可以判断
无法判断自定义类型

> Object.prototype.toString.call(null)
< "[object Null]"

> Object.prototype.toString.call(undefined)
< "[object Undefined]"

> Object.prototype.toString.call(false)
< "[object Boolean]"

> Object.prototype.toString.call(1)
< "[object Number]"

> Object.prototype.toString.call('1')
< "[object String]"

> Object.prototype.toString.call(Symbol())
< "[object Symbol]"

> Object.prototype.toString.call(console.log)
< "[object Function]"

> Object.prototype.toString.call([1,2,3])
< "[object Array]"

> Object.prototype.toString.call({1:'a'})
< "[object Object]"

实现一个判断数据类型的函数

单独判断 null
使用 typeof 判断出 原始类型
使用 Object.prototype.toString.call() 判断其他引用类型(无法判断自定义类型) 或者使用 instanceof 单独判断(可以判断自定义类型)

function judgeType(obj) {
	if(obj == null) {
	  return obj + ""
	}
	return typeof obj !== 'object' && typeof obj !== 'function' ? 
	typeof obj : obj instanceof Array ? 
	'array' : obj instanceof Function ? 
	'function' : 'object'
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值