判断数据类型

Object.prototype.toString.call(123).slice(8, -1) // Number


// 直接输出数类型 首字母大写 Number、Array、Function等

 

下面是各种数据类型调用toString()方法的返回值

数据类型例子return
字符串 “foo”.toString() “foo”
数字 1.toString() Uncaught SyntaxError: Invalid or unexpected token
布尔值 false.toString() “false”
undefined undefined.toString() Uncaught TypeError: Cannot read property ‘toString’ of undefined
null null.toString() Uncaught TypeError: Cannot read property ‘toString’ of null
String String.toString() “function String() { [native code] }”
Number Number.toString() “function Number() { [native code] }”
Boolean Boolean.toString() “function Boolean() { [native code] }”
Array Array.toString() “function Array() { [native code] }”
Function Function.toString() “function Function() { [native code] }”
Date Date.toString() “function Date() { [native code] }”
RegExp RegExp.toString() “function RegExp() { [native code] }”
Error Error.toString() “function Error() { [native code] }”
Promise Promise.toString() “function Promise() { [native code] }”
Obejct Object.toString() “function Object() { [native code] }”
Math Math.toString() “[object Math]”

 

所有类在继承Object的时候,改写了toString()方法。 Object原型上的方法是可以输出数据类型的。因此我们想判断数据类型时,也只能使用原始方法。

继而可使用这个方法去判断数据类型:

Object.prototype.toString.call(obj)

 

posted @ 2020-12-04 12:01  fanmengfei  阅读(97)  评论(0编辑  收藏  举报