1.Js判断数据类型的4种⽅式
Js数据类型 es5 6种数据类型:string、number、boolean、object(Data、function、Array)、null、undefined
Es6中新增了⼀种数据类型:symbol:表示独⼀⽆⼆的值,最⼤的⽤法是⽤来定义对象的唯⼀属性名,⽆论何时都不相等
var s1 = Symbol("symbol");
1.typeof
- 对于基本类型,除 null 以外,均可以返回正确的结果。
- 对于引⽤类型,除 function 以外,⼀律返回 object 类型。
- 对于 null ,返回 object 类型。
- 对于 function 返回 function 类型。
Typeof NaN = number
Typeof null = object
Typeof object = function Object/Array/String/Number/Boolean/Date/RegExp都是构造函数
Typeof {} = object
typeof console.log = ‘function’ 函数本身
typeof console.log() = ‘undefined’ 运⾏函数,默认返回undefined
2.instanceof
测试A是否是B的实例,⽐较A._proto是否和B.prototype相等
,instanceof 只能⽤来判断两个对象是否属于实例关系, ⽽不能判断⼀个对象实例具体属于哪种类型。
[] instanceof Array
{} instanceof Object
instanceof (A,B) = {
var L = A.__proto__;
var R = B.prototype;
if(L === R) {
// A的内部属性 __proto__ 指向 B 的原型对象
return true;
}
return false;
}
3.constructor
- null 和 undefined 是⽆效的对象,因此是不会有 constructor 存在的,这两种类型的数据需要通过其他⽅式来判断。
‘’.constructor === ‘String’
New Number(1).constructor === ‘Number’
New Function().constructor === ‘function’
4.toString
Object的原型⽅法,返回当前对象的[[Class]]
Object.prototype.toString.call(‘’) // [[Object String]]
Object.prototype.toString.call(new Error()) ; // [object Error]
Object.prototype.toString.call(document) ; // [object HTMLDocument]
Object.prototype.toString.call(window) ; //[object global] window 是全局对象 global 的引⽤