基本数据类型
值类型
number
、string
、null
、undefined
、boolean
引用类型
object
:({ },[ ],Math、Data、/^$/、实例对象)、function
检测数据类型
(以下将介绍四种检测方法)
typeof
instanceof
constructor
Object.prototype.toString.call([value])
方法一
typeof()
基于计算机底层数据类型的值(二进制)进行检测 。例如:对象以000开头…- 常用于基本数据类型的检测
- 缺点:
Object
类型不能进行具体检测
typeof(); //返回字符串
typeof(12); //"number"
typeof([1,2]);//"object"
typeof {} ; //"object"
typeof null //"object" !!!重点
typeof NaN //"number"
typeof undefined // "undefined"
方法二(右边必须为Object类型)
instanceof
用于检测具体的Object
类型,不能检测基本类型!!!
//instanceof
[] instanceof Array //true
function(){} instanceof Function //true
{} instanceof Object //true
1 instanceof Number //false
new Number(1) instanceof Number //true
"hahah" instanceof String //false
new String("hahah") instanceof String //true
null instanceof Object //false
- 底层机制:只要当前类出现在实例的原型链上的,返回值都为
true
(基于prototype
检测),因此,检测结果可能并不准确
function Fn(){
this.x = 100;
}
Fn.prototype = Object.create(Array.protptype)
let f = new Fn();
console.log(f instance of Array) //-->true
- 手写
instanceof
方法三
constructor
支持基本类型- 但也能修改,所以也不准确
("1").constructor === String //true
({}).constructor === Object //true
([]).constructor === Array //true
([]).constructor === Object //false
方法四
Object.prototype.toString.call()
标准检测数据类型的方法- 不是转化为字符串,时返回当前实例所属类型
let obj = { a:12 }
obj.toString() //=>[object Object]
Object.prototype.toString.call()
Object.prototype.toString.call(NaN) //->[object NaN]
Object.prototype.toString.call(null) //=>[object null]
自己封装
(function(){
var class2type = {};
var toStirng = class2type.toStirng;
["Boolean","Number","String","Function","Array","Date","RegExp","Object","Error","Symbol"]
.forEach(name => {
class2type[`[object ${name}]`] = name.toLowerCase;
})
function toType(obj){
if(obj==null) return obj+"";
return typeof obj==="object" || typeof obj==="function"?
class2type[toString.call(obj)] ||"object";
typeof obj;
}
window.toType = toType
})()