Sunny-117 / js-challenges

✨✨✨ Challenge your JavaScript programming limits step by step

Home Page:https://juejin.cn/column/7244788137410560055

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

数据类型判断

Sunny-117 opened this issue · comments

Object.prototype.toString.call(obj).slice(8, -1).toLowerCase()

commented
function getType(o) {
  const res = Object.prototype.toString.call(o);
  let str = Array.from(res.split(" ")[1]);
  str.pop();
  return str.join('');
}
function getType(data) {
    // [object ]
    let type = Object.prototype.toString.call(data)
    return type.substring(8, type.length-1)
}
  1. typeof运算符
  2. instanceof运算符
  3. Array.isArray()
  4. Object.prototype.toString.call()
  5. constructor
function getType(obj){
  let type  = typeof obj;
  if (type !== "object") {    // 先进行typeof判断,如果是基础数据类型,直接返回
    return type;
  }
  // 对于typeof返回结果是object的,再进行如下的判断,正则返回结果
  return Object.prototype.toString.call(obj).replace(/^\[object (\S+)\]$/, '$1'); 
}