js中的数据类型,以及如何检测数据类型

基本数据类型:string,number,boolean,null,undefined,symbol

引用数据类型:object(array,function...)

常用的检测数据类型的方法一般有以下三种:

1.typeof 一般主要用来检测基本数据类型,因为它检测引用数据类型返回的都是object

还需要注意的一点是:typeof检测null返回的也是object(这是JS一直以来遗留的bug)

typeof 1
"number"
typeof 'abc'
"string"
typeof true
"boolean"
typeof null
"object"
typeof undefined
"undefined"
typeof {}
"object"
typeof []
"object"

2.instanceof  这个方法主要是用来准确地检测引用数据类型(不能用来检测基本数据类型)

function add(){}
add instanceof Function
//true

var obj = {}
obj instanceof Object
//true

[] instanceof Array
//true

3.Object.prototype.toString()  可以用来准确地检测所有数据类型

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

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

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

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

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

Object.prototype.toString.call('111')
//"[object String]"

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

Object.prototype.toString.call(function add(){})
//"[object Function]"

 

posted @ 2019-08-28 00:55  前端南玖  阅读(2088)  评论(0编辑  收藏  举报