判断数据类型⼏种⽅法常⽤的判断数据类型的⽅法主要有:typeof,instanceof,constructor,String 下⾯来分别介绍
1、typeof:返回⼀个字符串,表⽰未经计算的操作数的类型。
console.log(typeof 42); // number
缺点:对于数组和对象或null 都会返回object
2、instanceof:⽤于测试构造函数的prototype属性是否出现在对象的原型链中的任何位置function Car(make, model, year) {
this.make = make;
}
var auto = new Car('Honda', 'Accord', 1998);
console.log(auto instanceof Car); // true
// 因为Object是原型链的最顶端,所以在其原型链上的都会为true
console.log(auto instanceof Object); // true
缺点:instanceof不能判断null和undefined
3、constructor:返回创建实例对象的 O bject构造函数的引⽤
var o = {};
var o = new Object;
var a = [];
函数prototype
var a = new Array;
var n = new Number(3);
function Tree(name) {
this.name = name;
}
var theTree = new Tree("Redwood");
console.log( structor ); //function Tree(name){this.name=name}
缺点:⽆法检测null,undefined
4、String
String.call(new Date) // [object Date]
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论