好!我叫戴向天。今天跟大家分享一个获取精准的数据类型的方法。
QQ:809002582
废话不多说。直接上代码↓↓↓
第一个参数就是需要获取数据类型的对象
第二个参数是进行判断该对象是不是指定的数据类型(默认没有)
当有第二个参数的时候,则就会进行返回布尔值 true | false ,没有就返回该数据的类型
/**
* 获取数据类型
* */
function getType (obj, str) {
let type = ''
if (Object.prototype.toString.call(obj) === '[object Array]') {
type = 'array'
} else if (Object.prototype.toString.call(obj) === '[object Boolean]') {
type = 'boolean'
} else if (Object.prototype.toString.call(obj) === '[object Number]') {
type = 'number'
} else if (obj instanceof HTMLElement) {
type = 'dom'
} else if (obj instanceof Map) {
type = 'map'
} else if (typeof (obj) == 'object' && Object.prototype.toString.call(obj).toLowerCase() == '[object object]' && !obj.length) {
type = 'json'
} else {
type = typeof (obj)
}
return str ? type === str : type
}
第二种方式:
function getType(o,s){
var toStr = Object.prototype.toString.call(o).toLowerCase();
var arr = toStr.match(/\w+/g)
var t = arr[1];
if (t === 'object' && toStr === '[object object]' && !o.length) t = 'json'
return s?t=== s.toLocaleLowerCase():t
}