js判断一个对象类型的方法

js判断一个对象的类型的方法

typeof:用于判断对象的类型,返回值为字符串

  1. ‘undefined’
  2. ‘boolean’
  3. ‘string’
  4. ‘number’
  5. ‘object’
  6. ‘function’
  7. ‘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]'

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值