javascript中怎么判断两个数据类型相等 您所在的位置:网站首页 欧拉拉使用方法 javascript中怎么判断两个数据类型相等

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

2024-06-24 03:49| 来源: 网络整理| 查看: 265

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

第二种

 



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有