Object.prototype.toString.call()
优点:可以检测所有基本数据类型,即使是 null和defined
缺点:不能精准判断自定义对象,对于自定义对象只会返回[object Object]
Object.prototype.toString.call() 常用于判断浏览器内置对象
- 每一个继承自
Object
的对象都有toString
方法,如果该方法没有被重写的话,就会返回[Object type]
(其中type为对象的类型) - 非
Object
类型的对象使用toString
时,会直接返回内容的字符串。
const an = ['Hello','An'];
an.toString(); // "Hello,An"
因此如果非Object
类型的对象需要使用toString
来判断对象类型时,需要使用call
或者apply
方法来改变toString
方法的执行上下文
const an = ['Hello','An'];
Object.prototype.toString.call(an); // "[object Array]"
Array.isArray()
缺点:只能判别数组
总结
Array.isArray()是ES5新增的方法,当不存在 Array.isArray() ,可以用 Object.prototype.toString.call() 判断
参考博客
前端面试题1:Object.prototype.toString.call() 、instanceof 以及 Array.isArray()三种方法判别数组的优劣和区别