js判断一个对象的类型的方法
typeof:用于判断对象的类型,返回值为字符串
- ‘undefined’
- ‘boolean’
- ‘string’
- ‘number’
- ‘object’
- ‘function’
- ‘symbol’
typeof(undefined) //typeof 语法有两种形式
typeof undefined // 'undefined'
typeof true // 'boolean'
typeof 'love' // 'string'
typeof 2 // 'number'
typeof null //'object'
typeof [] //'object'
typeof {} //'object'
typeof function(){} //'function'
typeof Symbol()
typeof Symbol('foo')
instanceof(基于原型链)
语法:obj instanceof Object
function test(){ }
var obj = {name:'js'}
var reg = /\d+/;
var date = new Date()
test instanceof Function
obj instanceof Object
reg instanceof RegExp
date instanceof Date
constructor
var num = 2;
num.__proto__.constructor === Number
num.constrcutor === Number
var date = new Date()
date.__proto__.constructor === Date
date.__proto__.__proto__.constructor === Object
date.__proto__.__proto__.__proto__.constructor === null
date.constructor === Date
Object.prototype.toString.call()
function test(){ }
var obj = {name:'js'}
var reg = /\d+/;
var date = new Date()
//能判断对象的具体类型
Object.prototype.toString.call(test) === '[object Function]'
Object.prototype.toString.call(obj) === '[object Object]'
Object.prototype.toString.call(reg) === '[object RegExp]'
Object.prototype.toString.call(date) === '[object Date]'
//六种基本数据类型
Object.prototype.toString.call(2) === '[object Number]'
Object.prototype.toString.call('javaScript') === '[object String]'
Object.prototype.toString.call(true) === '[object Boolean]'
Object.prototype.toString.call(null) === '[object Null]'
Object.prototype.toString.call(undefined) === '[object Undefined]'
Object.prototype.toString.call(Symbol()) === '[object Symbol]'