JS类型检测

135 阅读1分钟

typeof运算符

  • typeof适用于检测基本数据类型,但是对于null和对象都是返回object
  • 可以用来检测函数,对于函数返回 function

图片.png

  • 对于正则表达式返回 object

图片.png

typeof运算符的返回值类型是一个字符串类型,但是不能区分数组、对象和null。

instanceof运算符

不能用于判断基本数据类型,只能用于判断引用数据类型,判断构造函数的prototype属性所指向的对象是否存在另外一个要检测对象的原型链上

var a = []
a instanceof Array // true
a instanceof Object // true

var b = {}
b instanceof Array // false
b instanceof Object // true

var c = null
c instanceof Object // false  null 虽然是个特殊的对象,但是并不继承自 Object

constructor

不能用于undefined 和 null 的类型检测,因为两者没有构造函数

let a = 1

console.log(a.constructor === Number)//ture

console.log(''.constructor === String)//ture

console.log(true.constructor === Boolean)//ture

console.log([].constructor === Array)//ture

let b = {}

console.log(b.constructor === Object)//ture

console.log(/\d/.constructor === RegExp)//true

缺点:不准确

console.log([].constructor === Object)//false
console.log(/\d/.constructor === Object)//false

Object.prototype.toString.call()

每一个继承Object的对象都有toString方法,若toString方法没有重写则返回[Object type],其中type为对象的类型。 除Object类型的对象外,其他类型直接使用toString方法会直接返回内容的字符串,所以需要使用call或apply方法来改变toString方法的执行上下文 优点:对所有基本数据类型都能进行判断,包括 null 和 defined

console.log(Object.prototype.toString.call('a'))//[object String]

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

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

console.log(Object.prototype.toString.call(null))//[object Null]

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

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

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

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