javascript中怎么判断两个数据类型相等

在 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');

第二种方法
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值