typeof
能够快速区分基本数据类型 缺点:不能将Object、Array和Null区分,都返回object
typeof可以判断几种类型?
7种数据类型:`number、string、boolean、undefined、object、function` ,
以及 `ES6` 新增的 `symbol`
typeof能正确区分数据类型吗?
不能。对于原始类型,除 `null` 都可以正确判断;对于引用类型,除 `function` 外
都会返回 `"object"`
typeof注意事项
typeof返回值为string格式typeof未定义的变量不会报错,返回"undefiend"typeof(null) -> "object": 遗留已久的bugtypeof无法区别数组与普通对象:typeof([]) -> "object"typeof(NaN) -> "number"
- 列子
typeof(1); //'number'
typeof('1'); // 'string'
typeof(false); // 'boolean'
typeof(undefined); // 'undefined'
typeof(null); // 'object'
typeof([]); // 'object'
typeof({}); // 'object'
typeof(() => {}); // 'function'
instanceof
能够区分Array、Object和Function,适合用于判断自定义的类实例对象 缺点:Number,Boolean,String基本数据类型不能判断
语法
object instanceof constructor
参数
-
object某个实例对象
-
constructor某个构造函数
instanceof运算符用来检测constructor.prototype是否存在于参数object的原型链上。
// 定义构造函数
function C(){}
function D(){}
var o = new C();
o instanceof C; // true,因为 Object.getPrototypeOf(o) === C.prototype
o instanceof D; // false,因为 D.prototype 不在 o 的原型链上
o instanceof Object; // true,因为 Object.prototype.isPrototypeOf(o) 返回 true
C.prototype instanceof Object // true,同上
C.prototype = {};
var o2 = new C();
o2 instanceof C; // true
o instanceof C; // false,C.prototype 指向了一个空对象,这个空对象不在 o 的原型链上.
D.prototype = new C(); // 继承
var o3 = new D();
o3 instanceof D; // true
o3 instanceof C; // true 因为 C.prototype 现在在 o3 的原型链上
instanceof 常用来判断 A 是否为 B 的实例
Object.prototype.toString.call()
精准判断数据类型 缺点:写法繁琐不容易记,推荐进行封装后使用
toString.call(()=>{}) // [object Function]
toString.call({}) // [object Object]
toString.call([]) // [object Array]
toString.call('') // [object String]
toString.call(22) // [object Number]
toString.call(undefined) // [object undefined]
toString.call(null) // [object null]
toString.call(new Date) // [object Date]
toString.call(Math) // [object Math]
toString.call(window) // [object Window]
封装
const getPrototype = (item) => {
const prototype = Object.prototype.toString.call(item).split(' ')[1].replace(']', '');
return prototype
}