前端类型检测的方式

127 阅读1分钟

typeof 、instanceof、Object.prototype.toString

typeof

1.string

2.number

3.boolean

4.undefined

5.Object

  1. function

7.symbol

8.bigint

问题:

  1. typeof('abc')和 typeof 'abc'都是 string, 那么 typeof 是操作符还是函数?
    答:typeof 是操作符 如果 typeof 为 function,那么 typeof(typeof) 会返回'function'所以不是操作函数是操作符
    
  2. 既然 typeof 不是函数,那 typeof 后面的括号的作用是?
    答:括号的作用是进行分组而非函数的调用。—— 《javascript 高级程序设计》
    

instanceof

1 string

2 number

3 boolean

4 undefined

5 Object

6 function

7 symbol

8 bigint

9 array

10 Error

11 Regexp

12 Date

Object.prototype.toString.call()

1[object string]

2[object.number]

3[object undefined]

4[object boolean]

5[object null]

6[object object]

7[object function]

8[object Array]

9[object Date]

10[object Json]

11[object regExp]

12[object Error]

13[object Math]

14[object Arguments]

15[object BigInt]

16[object symbol]