Skip to main content

手写获取数据类型 typeof

思路:

  1. 防御性:为 null 直接 return
  2. typeof params 判断是否为对象
  3. 对象:Object.prototype.toString.call(value).slice(-8,1)
  4. 非对象 typeof params
function getType(params) {
// null排出
if(params === null) {return params + ''}
// object(数组/对象/函数/日期)都是对象,需要处理下 '[object Object]'
if(typeof params === "object"){
return Object.prototype.toString.call(params).slice(8,-1).toLowerCase() // object
}else{
// 非对象(string/number/boolen/undefined/symbool)
return typeof params;
}
}

使用方法:

console.log( getType(1) ) // number
console.log( getType("1") ) // string
console.log( getType(null) ) // null
console.log( getType(undefined) ) // undefined
console.log( getType({}) ) // object
console.log( getType(function(){}) ) // function