通过构造函数名称获取对象类型
当 typeof
运算符之一获得类型 object
时,它会陷入某种程度上……
在实践中,你可能需要将其缩小到它实际上是什么类型的对象,并且一种方法是使用对象构造函数名称来获取它实际上是什么样的对象:Object.prototype.toString.call(yourObject)
1.字符串
Object.prototype.toString.call("String")
“[object String]”
2.号码
Object.prototype.toString.call(42)
“[对象编号]”
布尔
Object.prototype.toString.call(true)
“[object Boolean]”
4.对象
Object.prototype.toString.call(Object())
或
Object.prototype.toString.call({})
“[object Object]”
5.功能
Object.prototype.toString.call(
function(){})
“[对象功能]”
6.日期
Object.prototype.toString.call(new Date(2015,10,21))
“[对象日期]”
7.正则表达式
Object.prototype.toString.call(new RegExp())
或
Object.prototype.toString.call(/foo/);
“[对象 RegExp]”
8.数组
Object.prototype.toString.call([]);
“[object Array]”
9.空
Object.prototype.toString.call(null);
“[对象无效]”
10.未定义
Object.prototype.toString.call(undefined);
“[对象未定义]”
11.错误
Object.prototype.toString.call(
Error());
“[对象错误]”