js数据类型和数据类型检测

js数据类型

  1. 简单(基本)类型:String、Number、Boolean、Undefined、Null、Symbol
  2. 引用(复杂)类型:Object、Array、Function

检测数据类型方法

typeof

一般用于检测基本数据类型,因为它检测引用(复杂)数据类型都会返回Objcet

1
2
3
4
5
6
7
8
9
console.log(typeof 1) // number
console.log(typeof '1') // string
console.log(typeof undefined) // undefined
console.log(typeof true) // boolean
console.log(typeof null) // object
function fun(){}
console.log(typeof fun) // function
var arr=[1,2,3,5]
console.log(typeof arr)// object

了解一下:typeof null返回值是object,因为js中的数据在底层是以二进制存储,如果前三位为0,那么就会判定为object,而null的所有都为0 ,所以null会被检测为object

instanceof

instanceof是一个双目判断运算符,a instanceOf b ,用来检测构造函数的prototype属性是否出现在对象原型链中的任意位置,返回一个布尔值。

1
2
3
4
5
6
7
let fun = function(){ }
console.log(fun instanceof Function) //true
let obj ={ }
console.log(obj instanceof Object) //true
let arr = [ ]
console.log(arr instanceof Array) //true
console.log(arr instanceof Object) //true

这个方法主要是用来检测复杂数据类型的,不能用来检测基本数据类型,可以理解为用来检测构造函数的prototype属性是否出现在对象原型链中的任意位置,只要在当前实例的原型链上,我们用其检测出来的结果都是 true。在类的原型继承中,我们最后检测出来的结果未必准确。。

1
2
1 instanceof Number //false 
null instanceof Object // false

instanceof运算符直接访问的变量的原始值,不会自动建立包装类。因此不能用来判断基本数据类型。

constructor

语法:实例.constructor

对象的原型链下(构造函数的原型下)有一个属性,叫constructor, constructor 作用和 instanceof 非常相似。但 constructor 检测 Object 与 instanceof 不一样,还可以处理基本数据类型的检测。

缺点:constructor并不可靠,因为它容易被修改。

Object.prototype.toString.call()

Object.prototype.toString.call()应该是目前最准确最常用的方式了,可以用来检测所有数据类型。在Object.prototype上有一个toString方法,这个方法执行的时候,会返回方法中this关键字对应数据值的数据类型,

1
2
//Object.prototype.toString() ->返回的是 Object.prototype 的数据类型 ->"[object Object]"
//f.toString() ->返回的是f的数据类型 ->"[object Object]"

也就是,我想知道谁的所属类信息,我们就把这个toString方法执行,并且让this变为我们检测的这个数据值,那么方法返回的结果就是当前检测这个值得所属类信息

1
2
3
4
5
6
7
8
9
10
11
12
13
Object.prototype.toString.call(12)//[boject Number]

Object.prototype.toString.call(true)//[boject Boolean]
//"[object Number]"
//"[object String]"
//"[object Object]"
//"[object Function]"
//"[object Undefined]"
//"[object Null]"
//"[object RegExp]"
//"[object Boolean]"
......