美文网首页
js中判断变量类型的终极(通用)方法来了

js中判断变量类型的终极(通用)方法来了

作者: 大兵_HERG | 来源:发表于2019-08-12 17:58 被阅读0次

1.第一种

function typeFn (any) {
  return Object.prototype.toString.call(any).slice(8, -1).toLowerCase();
}
//返回值为小写的["string", "number", "boolean", "undefined", "null", "object", "array", "function", "regexp"]任意一种

2.第二种

function getDataType (data){
 const typeMap = {
    '[object String]': 'string',
    '[object Number]': 'number',
    '[object Boolean]': 'boolean',
    '[object Undefined]': 'undefined',
    '[object Null]': 'null',
    '[object Object]': 'object',
    '[object Array]': 'array',
    '[object Function]': 'function'
  }
  return typeMap[Object.prototype.toString.call(data)]
}
//此方法更为直观一些

相关文章

网友评论

      本文标题:js中判断变量类型的终极(通用)方法来了

      本文链接:https://www.haomeiwen.com/subject/dofpjctx.html