javascript中类型检测的使用
javascript中类型检测的使用
1:typeof
使用:
typeof xxx
typeof 100 //"number"
typeof NaN //"number"
typeof "str"//"string"
typeof true //"boolean"
typeof function //"function"
typeof new Object()//"object"
typeof [1,2] //"object"
typeof null //"object"
typeof undefined //"undefined"
2:instanceof
使用:
obj instanceof Object
[1,2] instanceof Array //true
new Object() instanceof Array //false
example:
输入:
function Person(){}
function Student(){}
Student.prototype = new Person()
Student.prototype.constructor = Student
var person = new Student()
person instanceof Student // true
person instanceof Person // true
var student = new Person()
student instanceof Student // false
student instanceof Person // true
注意:
不同ifream与widnow之间的对象不能使用instanceof检测
3:Object.prototype.toString
Object.prototype.toString.apply([]) === "[object Array]" //true
Object.prototype.toString.apply(function(){}) === "[object Function]" //true
Object.prototype.toString.apply(null) === "[object Null]" // true
Object.prototype.toString.apply(undefined) === "[object Undefined]"//true
ie6,7,8
Object.prototype.toString.apply(null) === "[object Object]" // true
4: constructor
var num = 5
num.constructor == Number //true
"hello".constructor == String //true
true.constructor == Boolean //true
[1,2].constructor == Array //true
function person(){}
person.constructor == Function //true
var person = {}
person.constructor == Object //true
var person = new Person()
person.constructor == Person //true
5: duce type
根据各种数据类型自己的特点判断