js中数据类型检测
2017-11-13 13:17
176 查看
我们熟知的类型检测方式有三种:
1.typeof:
用于检测基本数据类型string number布尔 undefined (不能用来检验复杂数据类型和null);
能检测:
1.undefined
console.log(typeof undefined);//undefined2.boolean
console.log(typeof true);//boolean3.string
console.log(typeof '9');//string4.number
console.log(typeof 5);//number5.function
console.log(typeof function(){});//function不能检测
1.null
console.log(typeof null);//object2.object
console.log(typeof {});//object3.Array
console.log(typeof []);//object2.instanceof
instanceof 用于判断一个变量是否某个对象的实例其中在判断function,array的时候会出错。
var a=new Array();console.log(a instanceof Object)
true
var a=function(){};console.log(a instanceof Object)
True
这并不是我们希望看到的,故我们使用Object.prototype.toString.call(数据名)来解决。
3.Object.prototype.toString.call(数据名);
var a = new Object();Object.prototype.toString.call(a);//[Object Object];
var a = new Array();
Object.prototype.toString.call(a);//[Object Array];
var a = function(){};
Object.prototype.toString.call(a);//[Object Function];
故我们可以通过原型的toString方法结合call来判断复杂数据类型。
相关文章推荐