如何判断js的数据类型
js数据类型
基本类型: String、Boolean、Number、null、undefined,Symbol
引用类型:Object、Function、Array
一共有6种方法
- typeof
- instanceof
- constructor
- Object.prototype.toString
- Array.isArray()
- 正则判断
1.typeof
typeof 可以对基本类型(除了null)进行判断
typeof 10 // number
typeof '张三' // string
typeof true // boolean
typeof undefined // undefined
typeof null // object
typeof new Function() // function
typeof [] // object
typeof {} // object
2.instanceof
instanceof 检测的是原型 instanceof 只能用来判断两个对象是否属于实例关系, 而不能判断一个对象实例具体属于哪种类型。
例 A instanceof B 判断 A 对象的原型链上是否有右边这个构造函数的 prototype 属性,返回一个布尔值
实现原理
instanceof(A, B) = {
const a = A._proto_
const b = B.prototype
return a === b ? true : false
}
例:
[] instanceof Array // true
[] instanceof Object // true
3.constructor
constructor 判断方法跟 instanceof 相似,但是 constructor 检测 Object 与 instanceof 不一样,constructor 还可以处理基本数据类型的检测,不仅仅是对象类型。
constructor 可以得知某个实例对象,到底是哪个构造函数产生的
let f = new F()
f.constructor === F // true
4.Object.prototype.toString
每个对象都有一个 toString() 方法
Object.prototype.toString.call('张三') // [object String]
Object.prototype.toString.call(10) // [object Number]
Object.prototype.toString.call(true) // [object Boolean]
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([]) // [object Array]
Object.prototype.toString.call(document) // [object HTMLDocument]
Object.prototype.toString.call(window) //[object Window]
5.Array.isArray()
Array.isArray() 用于确定传递的值是否是一个 Array, 返回值是布尔类型
6.正则判断
可以判断数组和对象
方法:
function myTypeof(data) {
const str = JSON.stringify(data)
if (/^{.*}$/.test(data)) {
return 'object'
}
if (/^\[.*\]$/.test(data)) {
return 'array'
}
}