- 检测数据类型的方式
在JS中检测数据类型有且只有以下这4种方法:
- typeof 用来检测数据类型的运算符
- instanceof 用来检测当前实例是否利属于某个类,用来判断对象。
- constructor 基于构造函数检测数据类型(也是基于类的方式)
4、Object.prototype.toString.call() 检测数据类型最好的办法
1)、typeof的规则
typeof 返回的是一个表达式的数据类型的字符串,
typeof返回结果为基本数据类型("number"、"string"、"boolean"、"undefined"、"object"、"function")
typeof 要检测的值 运算符
typeof null 返回值是"object",但是null并不是对象
为什么typeOf(null)=>"object" ?
答:000:object -> 001:integer -> 010:double -> 100:string ->110:boolean
JS第一个版本,单个值在栈中占有32个位存储单元,两部分组成:标记位和数据。当时只有这5种数据类型。null是个特殊的,在机器码中null的指针,从零到31位全都是零,标记位是零,标记位是零,标记位是零返回的就是零。
typeof undefined 返回值是"undefined"
typeof NaN 返回值是"number"
typeof {} 返回值是" object "
typeof function 返回值是"function"
typeof string 返回值是"string"
typeof boolean 返回值是"boolean"
typeof操作符(是操作符不是函数,括号()不是必须有)有局限性:
1)、typeof不能检测object下的具体细分的类型,返回的值全是"object" typeof [ ] "object"
typeof的一个面试题
console.log(typeof typeof typeof typeof [12, 23, 34]); // "string"
typeof [12, 23, 34] ==> "object"
typeof "object" ==> "string"
typeof "string" ==> "string"
因为typeof返回的首先是一个字符串,所以出现两个及以上的typeof同时使用的时候,最终结果一定是"string"
2)、instanceof
3)、constructor
4)、Object.prototype.toString.call()
本人是以网络视频与网络文章的方式自学的,并按自己理解的方式总结了学习笔记。有不正确之处请各位高手多多指点,一起学习进步。【VX:czlingyun 暗号:CSDN】