JS中识别变量类型方法

Object.prototype.toString()

可以识别的类型有:

// 以下是11种:
var number = 1;          // [object Number]
var string = '123';      // [object String]
var boolean = true;      // [object Boolean]
var und = undefined;     // [object Undefined]
var nul = null;          // [object Null]
var obj = {a: 1}         // [object Object]
var array = [1, 2, 3];   // [object Array]
var date = new Date();   // [object Date]
var error = new Error(); // [object Error]
var reg = /a/g;          // [object RegExp]
var func = function a(){}; // [object Function]

除此之外还有:

console.log(Object.prototype.toString.call(Math)); // [object Math]
console.log(Object.prototype.toString.call(JSON)); // [object JSON]
function a() {
    console.log(Object.prototype.toString.call(arguments)); // [object Arguments]
}
a();

Object.prototype.toString.call(Math) [object Math];

封装为判断函数

let classType = {}
"Boolean Number String Function Array Date RegExp Object Error Null Undefined".split(' ').map(item => {
  return classType['[object ' + item + ']'] = item.toLowerCase();
})
function type(obj) {
  //这里是为了兼容IE浏览器,
  //因为在IE中null和undefined会被Object.prototype.toString识别为object
  if (obj === null) {
    return obj + ''
  }
  
  return typeof obj === 'object' || typeof obj === 'function' ? classType[Object.prototype.toString.call(obj)] || "object" : typeof obj
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值