乐趣区

前端一些杂记

我们知道判断基本数据类型可以通过 typeof
typeof 2 //’number’
typeof ’32’ //’string’
typeof true //”boolean”
typeof undefined //”undefined”
let y=Symbol(‘s’)
typeof y //”symbol”
// 判断 null
typeof null//object
但是判断对象,不能用 typeof
let obj={}
typeof obj //”object”
let arr=[]
typeof arr//”object”

那我们用什么方法能判断是对象还是数组呢?Object.prototype.toString 为什么能判断类型呢

Object.prototype.toString.call(obj)//”[object Object]”
Object.prototype.toString.call(arr)//”[object Array]”
Object.prototype.toString.call(null) //”[object Null]”
Object.prototype.toString.call(/test/)//”[object RegExp]”
toString 每个对象都有一个 toString() 方法,当该对象被表示为一个文本值时,或者一个对象以预期的字符串方式引用时自动调用。默认情况下,toString() 方法被每个 Object 对象继承。如果此方法在自定义对象中未被覆盖,toString() 返回 “[object type]”,其中 type 是对象的类型
Object.toString.call(obj)
VM2372:1 Uncaught TypeError: Function.prototype.toString requires that ‘this’ be a Function
at Object.toString (<anonymous>)
at <anonymous>:1:17

那为什么 Objet.toString 会报错呢,原因是 Object 是构造函数,本身是没有 toString 的方法的,实际调用的是 Function.prototype.toString.call(param) , 这里需要的参数类型是函数,但是传了对象,所以会报错。
那还有哪些判断数组的方式呢
let arr=[]
arr instanceof Array //true
arr instanceof Object //true
这个也有弊端,就是没有办法区分是数组还是对象
arr.constructor === Object //false
arr.constructor===Array //true
Array.isArray
综上,Object.prototype.toString.call(params) 最靠谱

退出移动版