入坑前端不久,今天与大佬聊天时聊到了一个关于如何判断函数参数类型的话题,特此记录一下,最后一个确实是之前没有听过用过的,学习一下
-
typeof
typeof 可以判断js当中的基本数据类型,基本上可以满足开发需要,如:Number,String,Boolean,undefined
例:
typeof ("1");// "string"
typeof (1); // "number"
typeof (true);// "boolean"
let getNum; // 变量声明未赋值
typeof (getNum);// "undefined"
关于typeof 检测null为object据说是js设计之初遗留的一个bug,感兴趣的可以自行找度娘
-
instanceof
然而typeof 并不是万能的,如下:
typeof (null); // "object"
let arr = []
typeof (arr); // "object"
let str = new String("1")
typeof (str); // "object"
当用typeof 检测null类型,array类型和基本包装类型的时候发现输出的是object,而这个时候就需要用到instanceof了,instanceof一般用于检测复杂数据类型
arr instanceof Array; // true
str instanceof String; // true
let fn = function(){}
fn instanceof Function; // true
let obj = {}
obj instanceof Object; // true
-
constructor
查看对象对应的构造函数,object的每个实例都具有属性constructor,保存着用于创建当前对象的函数。
arr.constructor === Array; // true
str.constructor === String; // true
fn.constructor === Function; // true
obj.constructor === Object; // true
-
Object.prototype.toString.call()
Object.prototype.toString.call(str); // "[object String]"
Object.prototype.toString.call(1); // "[object Number]"
Object.prototype.toString.call(arr); // "[object Array]"
Object.prototype.toString.call(fn); // "[object Function]"
Object.prototype.toString.call(null); // "[object Null]"
let newStr;
Object.prototype.toString.call(newStr); // "[object Undefined]"
Object.prototype.toString.call()可以判断具体的对象类型,包括正则等,但是无法判断自定义对象类型。
最后关于 null,null 在 js 中是一个很特殊的存在,介于对象与非对象之间,为什么这么说呢,因为用 typeof 检测 null 会返回 object,这似乎说明 null 为 objec t类型,但是使用 instanceof 检测 null 是否为 Object 时会返回 false,这。。。
网传 null 是 js 在设计之初遗留的一个问题,其实我也不是很了解,毕竟太菜,哈哈哈,感兴趣的可以自行找度娘。最后欢迎大佬补充说明,第一次写博客,写的不好请各位大佬见谅。