js判断数据类型的五种方法

js判断数据类型的五种方法1 typeof 可以判断数据类型 它返回表示数据类型的字符串 返回结果只能包括 number boolean string function object undefined 可以使用 typeof 判断变量是否存在 如 if typeof a undefined

大家好,我是讯享网,很高兴认识大家。

1. typeof

  • 可以判断数据类型,它返回表示数据类型的字符串(返回结果只能包括number,boolean,string,function,object,undefined);
  • 可以使用typeof判断变量是否存在(如if(typeof a!="undefined"){...});
  • Typeof 运算符的问题是无论引用的对象是什么类型 它都返回object

typeof {} // object typeof [1,2] // object typeof /\s/ //object 

讯享网

2.instanceof

原理 因为A instanceof B 可以判断A是不是B的实例,返回一个布尔值,由构造类型判断出数据类型


讯享网

讯享网console.log(arr instanceof Array ); // true console.log(date instanceof Date ); // true console.log(fn instanceof Function ); // true //注意: instanceof 后面一定要是对象类型,大小写不能写错,该方法试用一些条件选择或分支 

3.通过Object下的toString.call()方法来判断

Object.prototype.toString.call(); console.log(toString.call(123)); //[object Number] console.log(toString.call('123')); //[object String] console.log(toString.call(undefined)); //[object Undefined] console.log(toString.call(true)); //[object Boolean] console.log(toString.call({})); //[object Object] console.log(toString.call([])); //[object Array] console.log(toString.call(function(){})); //[object Function] 

4.根据对象的contructor判断

讯享网console.log('数据类型判断' - constructor); console.log(arr.constructor === Array); //true console.log(date.constructor === Date); //true console.log(fn.constructor === Function); //true 

5.jq中判断数据类型的方法

jQuery提供了一系列工具方法,用来判断数据类型,以弥补JavaScript原生的typeof运算符的不足。以下方法对参数进行判断,返回一个布尔值。
jQuery.isArray();是否为数组
jQuery.isEmptyObject();是否为空对象 (不含可枚举属性)。
jQuery.isFunction():是否为函数
jQuery.isNumberic():是否为数字
jQuery.isPlainObject():是否为使用“{}”或“new Object”生成对象,而不是浏览器原生提供的对象。
jQuery.isWindow(): 是否为window对象;
jQuery.isXMLDoc(): 判断一个DOM节点是否处于XML文档中。

小讯
上一篇 2025-01-14 15:38
下一篇 2025-02-26 17:09

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/42762.html