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

Es6 谢支星
文章标签: Es6
1402

首先我们来了解一下js中的数据类型

基本数据类型:Undefined、Null、Boolean、Number、String(值类型)

复杂数据类型:Object(引用类型)

typeof

typeof返回的类型都是字符串形式,对于复杂的数据类型。只有是Function时,typeof返回的才是"Function",其它复杂类型返回的都是"Object",需要注意的是null 它的typeof返回的是"Object"

var a = "iamstring.";
var b = 222;
var c= [1,2,3];
var d = new Date();
var e = function(){alert(111);};
var f = function(){this.name="22";};

typeof a ------------> string
typeof b ------------> number
typeof c ------------> object
typeof d  ------------> object
typeof e ------------> function
typeof f ------------> function

instanceof

instanceof是判断已知对象类型的方法(instanceof 后面一定要是对象类型,并且大小写不能错,该方法适合一些条件选择或分支。)

语法: a instanceof b  就是判断 a 是不是b类型的数据

c instanceof Array---------------> true
d instanceof Date---------------> true
f instanceof Function ------------> true
f instanceof function------------> false

根据对象的constructor判断

c.constructor === Array ----------> true
d.constructor === Date -----------> true
e.constructor === Function -------> true

注意: constructor 在类继承时会出错


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

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