JavaScript怎么判断数据类型?8 种方式分享

 1311

JavaScript怎么判断数据类型?本篇文章给大家分享JS 判断数据类型的 8 种方式,有效帮助工作和面试,面试官看了微微一笑。


JavaScript怎么判断数据类型?8 种方式分享


1、typeof

只能识别基础类型和引用类型

注意:null、 NaN、 document.all 的判断

console.log(typeof null); // object
console.log(typeof NaN); // number
console.log(typeof document.all); // undefined


2、constructor

constuctor 指向创建该实例对象的构造函数

注意 null 和 undefined 没有 constructor,以及 constructor 可以被改写

String.prototype.constructor = function fn() {
  return {};
};
 
console.log("云牧".constructor); // [Function: fn]


3、instanceof

语法:obj instanceof Type

功能:判断 obj 是不是 Type 类的实例,只可用来判断引用数据

实现思路: Type 的原型对象是否是 obj 的原型链上的某个对象

注意:右操作数必须是函数或者 class

手写 instanceof

function myInstanceof(Fn, obj) {
  // 获取该函数显示原型
  const prototype = Fn.prototype;
  // 获取obj的隐式原型
  let proto = obj.__proto__;
  // 遍历原型链
  while (proto) {
    // 检测原型是否相等
    if (proto === prototype) {
      return true;
    }
    // 如果不等于则继续往深处查找
    proto = proto.__proto__;
  }
  return false;
}


4、isPrototypeof

是否在实例对象的原型链上

基本等同于 instanceof

console.log(Object.isPrototypeOf({})); // false
console.log(Object.prototype.isPrototypeOf({})); // true  期望左操作数是一个原型,{} 原型链能找到 Object.prototype


5、Object.prototype.toString

利用函数动态 this 的特性

function typeOf(data) {
  return Object.prototype.toString.call(data).slice(8, -1);
}
 
// 测试
console.log(typeOf(1)); // Number
console.log(typeOf("1")); // String
console.log(typeOf(true)); // Boolean
console.log(typeOf(null)); // Null
console.log(typeOf(undefined)); // Undefined
console.log(typeOf(Symbol(1))); // Symbol
console.log(typeOf({})); // Object
console.log(typeOf([])); // Array
console.log(typeOf(function () {})); // Function
console.log(typeOf(new Date())); // Date
console.log(typeOf(new RegExp())); // RegExp


6、鸭子类型检测

检查自身属性的类型或者执行结果的类型

通常作为候选方案

例子:kindof 与 p-is-promise

p-is-promise:

const isObject = value =>
  value !== null && (typeof value === "object" || typeof value === "function");
 
export default function isPromise(value) {
  return (
    value instanceof Promise ||
    (isObject(value) && typeof value.then === "function" && typeof value.catch === "function")
  );
}

kindof:

function kindof(obj) {
  var type;
  if (obj === undefined) return "undefined";
  if (obj === null) return "null";
 
  switch ((type = typeof obj)) {
    case "object":
      switch (Object.prototype.toString.call(obj)) {
        case "[object RegExp]":
          return "regexp";
        case "[object Date]":
          return "date";
        case "[object Array]":
          return "array";
      }
 
    default:
      return type;
  }
}


7、Symbol.toStringTag

原理:Object.prototype.toString 会读取该值

适用场景:需自定义类型

注意事项:兼容性

class MyArray {
  get [Symbol.toStringTag]() {
    return "MyArray";
  }
}
 
const arr = new MyArray();
console.log(Object.prototype.toString.call(arr)); // [object MyArray]


8、等比较

原理:与某个固定值进行比较

适用场景:undefined、 window、 document、 null 等

underscore.js:

JavaScript怎么判断数据类型?8 种方式分享


总结

方法基础数据类型引用类型注意事项
typeof×NaN、object、document.all
constructor√ 部分可以被改写
instanceof×多窗口,右边构造函数或者class
isPrototypeof×小心 null 和 undefined
toString小心内置原型
鸭子类型-不得已兼容
Symbol.toString Tag×识别自定义对象
等比较特殊对象


加餐:ES6 增强的 NaN

NaN 和 Number.NaN 特点

typeof 后是数字

自己不等于自己

delete 不能被删除

isNaN

如果非数字,隐式转换传入结果如果是 NaN,就返回 true,反之返回 false

console.log(isNaN(NaN)); // true
console.log(isNaN({})); // true

Number.isNaN

判断一个值是否是数字,并且值是否等于 NaN

console.log(Number.isNaN(NaN)); // true
console.log(Number.isNaN({})); // false

其他判断是否 NaN 的方法

function isNaNVal(val) {
  return Object.is(val, NaN);
}
 
function isNaNVal(val) {
  return val !== val;
}
 
function isNaNVal(val) {
  return typeof val === "number" && isNaN(val);
}
 
// 综合垫片
if (!("isNaN" in Number)) {
  Number.isNaN = function (val) {
    return typeof val === "number" && isNaN(val);
  };
}

indexOf 和 includes

indexOf 不可查找 NaNincludes 则可以

const arr = [NaN];
 
console.log(arr.indexOf(NaN)); // -1
console.log(arr.includes(NaN)); // true


本文网址:https://www.zztuku.com/detail-13838.html
站长图库 - JavaScript怎么判断数据类型?8 种方式分享
申明:本文转载于《掘金社区》,如有侵犯,请 联系我们 删除。

评论(0)条

您还没有登录,请 登录 后发表评论!

提示:请勿发布广告垃圾评论,否则封号处理!!

    编辑推荐