ES6-js数据判断类型的几种方法

es6 袁德灿

前言:

判断js中的数据类型有以下几种方法:typeofinstanceof constructor prototype$.type()/jquery.type()

先举几个例子:

var a = "iamstring.";
var b = 222;
var c= [1,2,3];
var d = new Date();

//1、最常见的判断方法:typeof
alert(typeof a)  ------------> string
alert(typeof b)  ------------> number

//2、判断已知对象类型的方法: instanceof
alert(c instanceof Array) ---------------> true
alert(d instanceof Date);

//3、根据对象的constructor判断: constructor
alert(c.constructor === Array) ----------> true
alert(d.constructor === Date) -----------> true
//注意: constructor 在类继承时会出错

//4、通用但很繁琐的方法: prototype
alert(Object.prototype.toString.call(a) === ‘[object String]') -------> true;
alert(Object.prototype.toString.call(b) === ‘[object Number]') -------> true;


//5、无敌万能的方法:jquery.type()
jQuery.type( undefined ) === "undefined";
jQuery.type() === "undefined";

通常情况下用typeof 判断就可以了,遇到预知Object类型的情况可以选用instanceof或constructor方法,实在辙就使用$.type()方法。

推荐一个技术之家的一个博客地址: https://www.jb51.net/article/102972.htm

还能输出{{restrictNumber}}个字符  
  • {{reply.author}}

    {{CommonUtil.formateDate(reply.ac_CommentDate).shortTime}}
  • 回复了{{Comments.author}} :