js判断数据类型
在js中如果想判断某种数据的数据类型,一般使用typeof方法
var str = "string"; var num = 1; var bool = true; var u; var n = null; var nan = NaN; var obj = new Object(); var fn = function () {}; console.log(typeof str); //string console.log(typeof num); //number console.log(typeof bool); //boolean console.log(typeof u); //undefined console.log(typeof n); //object console.log(typeof nan); //number console.log(typeof obj); //object console.log(typeof fn); //function
注:NaN的类型是number
但是如果是数组、对象或者正则用typeof方法则无法区分
var arr = [1,2]; var obj = {};var reg = /^\d{11}$/; console.log(typeof arr); //object console.log(typeof obj); //object console.log(typeof reg); //object
因为所有引用类型的值都是Object的实例,所以要判断引用类型的具体数据类型要使用instanceof方法:
var arr = [1,2]; var obj = {}; var reg = /^\d{11}$/; console.log(arr instanceof Array) //true console.log(obj instanceof Object); //true console.log(reg instanceof RegExp); //true