数据类型检测

typeof

  • 基本类型返回的都是小写的字符串
  • 引用类型无法区分是普通对象还是数组对象,返回都是'object',函数是'function'
typeof [];  //  'object'
typeof {};  //  'object'
typeof true // 'boolean'
typeof 1; //  'number'
typeof NaN;  //  'number'
typeof ''  //  'string'
typeof null //  'object'
typeof undefined //  'undefined'
typeof function () {};  // 'function'

instanceof


Object.prototype.toString.call()

  • 这个是检测数据类型最好,最全面的的方法了
Object.prototype.toString()      //  '[object Object]'
Object.prototype.toString.call()      //  "[object Undefined]"
Object.prototype.toString.call([])      //  '[object Array]'  注意第二个是大写开头
Object.prototype.toString.call({})      //  '[object Object]'
Object.prototype.toString.call(true)      //  '[object Boolean]'
Object.prototype.toString.call(1)      //  '[object Number]'
Object.prototype.toString.call(NaN)   //  '[object Number]'
Object.prototype.toString.call('')       //  '[object String]'
Object.prototype.toString.call(null)       //  '[object Null]'
Object.prototype.toString.call(undefined)      //  '[object Undefined]'
posted @ 2020-11-10 00:01  飞行者二鸭  阅读(98)  评论(0编辑  收藏  举报