常见的数据类型有好几种,比如undefined类型,字符串类型,null类型,布尔类型,数字类型,对象类型,Symbol类型,时间类型等。我们类型有这么多,我们主要是分类俩大类:
基本类型:String、Number、Boolean、Symbol、Undefined、Null 等等
引用类型:Object Function 、Array、RegExp、Date 等等
很多时候面试的时候面试官都比较喜欢问检验数据类型的几种方法,那今天我们就来介绍一下。
首先我们来定义几种数据类型代码如下:
var a;
var b = "花括号";
var c = 1;
var d = false;
var e = [1, 2, 3];
var f = { name: "渣渣辉" };
var g = new Date;
var h = function () {
return 5;
}
我们定义的几种数据,现在我们来检验一下。
1. typeof 检验
typeof是我们常用的检验方式,我们来看看代码:
console.log(typeof a)
console.log(typeof b)
console.log(typeof c)
console.log(typeof d)
console.log(typeof e)
console.log(typeof f)
console.log(typeof g)
console.log(typeof h)
结果如下:
结果如上,发现数组,对象,时间类型这几个都是object对象类型。对于基本类型,除 null 以外,均可以返回正确的结果。对于引用类型,除 function 以外,一律返回 object 类型。对于 function 返回 function 类型。
2.instanceof 检验
instanceof 是用来判断 A 是否为 B 的实例,表达式为:A instanceof B,如果 A 是 B 的实例,则返回 true,否则返回 false。 在这里需要特别注意的是:instanceof 检测的是原型。
来看下代码:
console.log(a instanceof undefined) //报错
console.log(b instanceof String);
console.log(c instanceof Number);
console.log(d instanceof Boolean);
console.log(e instanceof Array);
console.log(f instanceof Object);
console.log(g instanceof Object);
console.log(h instanceof Object)
来看看结果:
我们发现除了第一个报错,其他的都可以,通过例子证明 instanceof 只能用来判断两个对象是否属于实例关系, 而不能判断一个对象实例具体属于哪种类型。简单的说就是检验对象必须满足是对象类型,再来检验是对象类型里的那种。
3.constructor 检验
constructor检验是通过构造函数检验的,来看下代码:
console.log(a.constructor == undefined) //报错
console.log(b.constructor == String);
console.log(c.constructor==Number);
console.log(d.constructor == Boolean);
console.log(e.constructor==Array);
console.log(f.constructor == Object);
console.log(g.constructor == Date);
console.log(h.constructor == Function)
代码如上,除了第一个报错我们来看看结果:
用我们的变量点出构造函数constructor等于我们的数据类型,满足返回true,否则返回false。
4.tostring 检验
toString() 是 Object 的原型方法,调用该方法,默认返回当前对象的 [[Class]] 。返回格式[object Xxx] ,其中 Xxx 就是对象的类型。
tostring检验是通过object点出原型prototype再点出我们的tostring在点call方法,返回正确的对应数据类型。代码如下:
console.log(Object.prototype.toString.call(a));
console.log(Object.prototype.toString.call(b));
console.log(Object.prototype.toString.call(c));
console.log(Object.prototype.toString.call(d));
console.log(Object.prototype.toString.call(e));
console.log(Object.prototype.toString.call(f));
console.log(Object.prototype.toString.call(g));
console.log(Object.prototype.toString.call(h));
来看看我们的结果:
结果如上。
5.万能方法 jquery.type() 检验
这是一个可以说是万能的方法,使用这个前提要引用jq文件。jquery.type()方法比较实用,直接用就可以了。
代码如下:
console.log(jQuery.type(a) === "undefined")
console.log(jQuery.type(b) === "string")
console.log(jQuery.type(c) === "number")
console.log(jQuery.type(d) === "boolean")
console.log(jQuery.type(e) === "array")
console.log(jQuery.type(f) === "object")
console.log(jQuery.type(g) === "date")
console.log(jQuery.type(h) === "function")
直接用jquery点出type方法,把我们的变量放进去===我们的数据类型,满足返回true,否返回false。结果如下:
结果如上,这是我们几种常用的方法,其中还有其他的,比如isNaN可以检验数字类型,非数字返回true,否则返回false。还有isArray()是检验数组的,检验数数组返回true,否则返回false。还有一些其他的就不一一列举了。今天的介绍就到这里,以上纯属个人观点见解,如有错误欢迎指正。谢谢大家。