JavaScript之检测数据类型(面试必须掌握)

一、typeof 用于基本数据类型检测准确率较高(typeof 无法用于引用类型检测)

1、基本数据
console.log(typeof '123')    //string
console.log(typeof 1)        //number
console.log(typeof true)     //boolean
2、函数--'function'

什么是函数:函数名();

console.log(typeof console.log)  //function
console.log(typeof  alert )      //function
3、未定义变量--'undefined'
let a;
console.log(typeof  a)   //undefined
4、对象 -- 'object'
let obj = {
      name: 'obj',
    }
console.log(typeof obj)    //object
console.log(typeof null)   //object

提示:null--'object'这是由于历史原因造成的。1995年的 JavaScript 语言第一版,只设计了五种数据类型(对象、整数、浮点数、字符串和布尔值),没考虑null,只把它当作object的一种特殊值。后来null独立出来,作为一种单独的数据类型,为了兼容以前的代码,typeof null返回object就没法改变了。

二、instanceof 检测出是谁的实例

1、instanceof 后跟的是构造函数名称
2、instanceof 关键字 返回一个布尔值
3、instanceof 检测不准确,所有对象(function array object 基本包装类型)都是Object的实例

console.log(arr instanceof Array);      //true

console.log(obj instanceof Object);     //true

console.log(obj instanceof Array);      //false

console.log(arr instanceof Object);     //true

var num = new Number('23');        
console.log(num instanceof Number);     //true
console.log(num instanceof Object);     //true

三、Object.prototype.toString方法

定义函数:

function getClass(o) {
    return Object.prototype.toString.call(o).slice(8, -1).toLowerCase();
}

使用函数

console.log(getClass(123));        //number

console.log(getClass('abc'));      //string

console.log(getClass(true));       // boolean

console.log(getClass({}));         //object

console.log(getClass([]));         //array

console.log(getClass(null));       //null

console.log(getClass(undefined));  //undefined

或者直接使用

console.log(Object.prototype.toString.call(123));            //[object Number]
console.log(Object.prototype.toString.call('123'));          //[object String]
console.log(Object.prototype.toString.call(undefined));      //[object Undefined]
console.log(Object.prototype.toString.call(true));           //[object Boolean]
console.log(Object.prototype.toString.call({}));             //[object Object]
console.log(Object.prototype.toString.call([]));             //[object Array]
console.log(Object.prototype.toString.call(function() {}));  //[object Function]
console.log(Object.prototype.toString.call(null));           //[[object Null]]
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容