在 JavaScript 里使用 typeof 来判断数据类型,只能区分基本类型,即 “number”,”string”,”undefined”,”boolean”,”object”,“function” 六种。
对于数组、null、对象来说,其关系错综复杂,使用 typeof 都会统一返回 “object” 字符串。
要想区别对象、数组、函数单纯使用 typeof 是不行的,JavaScript中,通过Object.prototype.toString方法,判断某个对象值属于哪种内置类型。
在介绍Object.prototype.toString方法之前,
先把toString()方法和Object.prototype.toString.call()方法进行对比。
var arr=[1,2];
//直接对一个数组调用toString()
arr.toString();// "1,2"
//通过call指定arr数组为Object.prototype对象中的toString方法的上下文
Object.prototype.toString.call(arr); //"[object Array]"
Object.prototype.toString.call(arr); //"[object Array]" 判断是否是数组
精确判断对象的类型
JavaScript 中一切都是对象,任何都不例外,对所有值类型应用 Object.prototype.toString.call() 方法结果如下:
console.log(Object.prototype.toString.call("jerry"));//[object String]
console.log(Object.prototype.toString.call(12));//[object Number]
console.log(Object.prototype.toString.call(true));//[object Boolean]
console.log(Object.prototype.toString.call(undefined));//[object Undefined]
console.log(Object.prototype.toString.call(null));//[object Null]
console.log(Object.prototype.toString.call({name: "jerry"}));//[object Object]
console.log(Object.prototype.toString.call(function(){}));//[object Function]
console.log(Object.prototype.toString.call([]));//[object Array]
console.log(Object.prototype.toString.call(new Date));//[object Date]
console.log(Object.prototype.toString.call(/\d/));//[object RegExp]
function Person(){};
console.log(Object.prototype.toString.call(new Person));//[object Object]
原文链接:https://blog.csdn.net/qq_39408204/article/details/91492061