在 JavaScript 中, 判断一个变量的类型尝尝会用 typeof 运算符, 在使用 typeof 运算符时采用引用类型存储值会出现一个问题, 无论引用的是什么类型的对象, 它都返回 "object".
所以怎么才能判断两个类型相等呢?
instanceof 来解决这个问题. instanceof 运算符与 typeof 运算符相似, 用于识别正在处理的对象的类型. 与 typeof 方法不同的是, instanceof 方法要求开发者明确地确认对象为某特定类型. 例如:
- var oStringObject = new String("hello world");
- console.log(oStringObject instanceof String); // 输出 "true"
下面是我简单封装了一下
第一种
- function fn(arg1,arg2){
- if(arg1===undefined||arg1===null){
- console.log('无值')
- }else{
- if( arg2!=undefined||arg2!=null ){
- console.log(2)
- }else{
- if(typeof arg1 =='string'){
- console.log(1)
- }
- if( arg1 instanceof Array ){
- console.log(4)
- }
- if( arg1 instanceof Object ){
- console.log(3)
- }
- }
- }
- }
- fn('hello');
- fn({});
- fn([]);
- fn();
- fn('hello','world');
第二种
来源: https://www.cnblogs.com/cc1410039105/p/12521396.html