js 精准获取数据类型加判断 - 戴向天

180 阅读1分钟

大家好!我叫戴向天

QQ群:602504799

如若有不理解的,可加QQ群进行咨询了解

// 获取数据类型的方法
// 获取数据类型的方法
function getType (o, s = null) {
  let t = Object.prototype.toString.call(o).split(' ')[1]
  t = t.substring(0, t.length - 1).trim().toLowerCase()
  if (t === 'object' && Object.prototype.toString.call(o).toLowerCase() === '[object object]' && !o.length) t = 'json'
  return s ? t === s : t
}
​
console.log(getType({}))
console.log(getType({},'json'))
console.log(getType({},'array'))
console.log(getType([]))
console.log(getType([],'array'))
console.log(getType(''))
console.log(getType('','string'))
console.log(getType(0))
console.log(getType(0,'number'))