javascript中的类型检测

最常见的是使用 typeof 来判断数据类型

可以区分4种基本类型,即 “number”,”string”,”undefined”,”boolean”,第5种基本类型null类型返回值为object(历史兼容性问题导致)

判断对象类型时返回为object

1 console.log(typeof 'hello') //string
2 console.log(typeof('hello')) //string            
3 console.log(typeof 123) //number
4 console.log(typeof undefined) //undefined
5 console.log(typeof null) //object
6 console.log(typeof [1,2])  //object
7 console.log(typeof new Object()) //object
8 console.log(typeof NaN) //number

typeof在判断一些基本类型或函数对象时很方便,但不能判断其他类型的对象,此时使用instanceof(在不同iframe和window间检测时失效)

 1 console.log([1,2] instanceof Array) //true
 2 console.log(new Object() instanceof Array) //false
 3 function Person(){  //父类
 4 }
 5 function Student(){  //子类
 6 }
 7 //任何一个构造函数都会有一个prototype对象属性
 8 //这个对象属性将用作使用new构造函数去构造出对象的原型
 9 Student.prototype = new Person();
10 Student.prototype.constructor = Student;
11 var s = new Student();            
12 var p = new Person();
13 console.log(s instanceof Student) //true
14 console.log(p instanceof Person)  //true
15 console.log(p instanceof Student)  //false
16 //对象s有一个原型,指向它的构造器Student.prototype属性
17 //对象s的原型不等于Person.prototype属性,于是原型链向上查找
18 //对象s的原型的原型Student.prototype.prototype等于Person.prototype,因此返回true
19 console.log(s instanceof Person)  //true

想区别对象、数组、函数使用 typeof 是不行的,js中,通过Object.prototype.toString.apply()方法,判断某个对象值属于哪种内置类型

1 console.log(Object.prototype.toString.apply([])); //"object Array"
2 console.log(Object.prototype.toString.apply(function(){}));  //"object Function"
3 console.log(Object.prototype.toString.apply(null));  //"object Null" IE6/7/8下返回"object Object"
4 console.log(Object.prototype.toString.apply(undefined)); //"object Undefined" 

猜你喜欢

转载自www.cnblogs.com/yaotome/p/9254760.html