【判断JS数据类型】
- JS 类型
1 null 2 undefined 3 boolean 4 number 5 string 6 引用类型(object、array、function) 7 symbol
1.判断JS类型--typeof
判断 typeof(null) 时值为 'object'; 判断数组和对象时值均为 'object'
1 const a = () => { 2 return true 3 } 5 typeof a 6 "function" 7 typeof 3 8 "number" 9 typeof '3' 10 "string" 11 typeof [3] 12 "object" 13 typeof {b: '3'} 14 "object" 15 typeof undefined 16 "undefined" 17 typeof null 18 "object"
2.判断JS类型 - Object.prototype.toString.call
对于所有基本的数据类型都能进行判断
1 Object.prototype.toString.call(undefined) 2 "[object Undefined]" 3 Object.prototype.toString.call(null) 4 "[object Null]" 5 Object.prototype.toString.call(123) 6 "[object Number]" 7 Object.prototype.toString.call("123") 8 "[object String]" 9 Object.prototype.toString.call({}) 10 "[object Object]" 11 Object.prototype.toString.call([]) 12 "[object Array]" 13 Object.prototype.toString.call(a) 14 "[object Function]" 15 Object.prototype.toString.call(new Date()) 16 "[object Date]" 17 Object.prototype.toString.call(Symbol()) 18 "[object Symbol]" 19 Object.prototype.toString.call(Math) 20 "[object Math]"
3.判断JS类型 - instanceof
这种方式只适合判断object类型
1 const b = [] 2 b instanceof Array 3 true 4 b instanceof Object 5 true 6 b instanceof Function 7 false 8 -------------- 9 const c = {} 10 c instanceof Array 11 false 12 c instanceof Object 13 true 14 c instanceof Function 15 false 16 ------------- 17 a instanceof Array 18 false 19 a instanceof Object 20 true 21 a instanceof Function 22 true