>  기사  >  웹 프론트엔드  >  JavaScript는 데이터 유형을 어떻게 결정합니까? 공유하는 8가지 방법

JavaScript는 데이터 유형을 어떻게 결정합니까? 공유하는 8가지 방법

青灯夜游
青灯夜游앞으로
2023-02-16 14:48:384556검색

JavaScript는 데이터 유형을 어떻게 결정하나요? 이 기사에서는 JS를 사용하여 업무와 면접에 효과적으로 도움이 되는 데이터 유형을 결정하는 8가지 방법을 공유합니다. 면접관은 이 기사를 읽은 후 살짝 미소를 지었습니다.

JavaScript는 데이터 유형을 어떻게 결정합니까? 공유하는 8가지 방법

1. typeof

  • 는 기본 유형과 참조 유형만 인식할 수 있습니다

참고: null, NaN, document.all code code> 판단<code>nullNaNdocument.all 的判断

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

2、constructor

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

注意 nullundefined 没有 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、鸭子类型检测

  • 检查自身属性的类型或者执行结果的类型
  • 通常作为候选方案
  • 例子:kindofp-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、等比较

  • 原理:与某个固定值进行比较
  • 适用场景:undefinedwindowdocumentnull

underscore.js:

总结

方法 基础数据类型 引用类型 注意事项
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

    2. constructor

constructor는 인스턴스 객체를 생성하는 생성자를 가리킵니다

참고null 및 undefine에는 생성자가 없으며 생성자는 재정의될 수 있습니다🎜rrreee

3.instanceof🎜🎜🎜 구문: obj instanceof Type🎜🎜기능: objType의 인스턴스인지 확인 code> 클래스를 판단하는 데만 사용할 수 있습니다.🎜🎜구현 아이디어: Type의 프로토타입 개체가 obj🎜🎜의 프로토타입 체인에 있는 개체인지 여부 : 올바른 피연산자는 함수 또는 클래스여야 합니다🎜🎜🎜손으로 쓴 instanceof:🎜rrreee

4. IsPrototypeof🎜🎜🎜 인스턴스 객체의 프로토타입 체인🎜🎜기본적으로 instanceof🎜🎜rrreee

5와 동일합니다. Object.prototype.toString🎜🎜🎜을 사용하세요. 동적 this 함수의 특징🎜🎜rrreee

6. Duck 유형 감지🎜🎜🎜자신의 속성 유형이나 실행 결과 유형을 확인하세요🎜🎜보통 후보 솔루션🎜🎜예: kindof p-is-promise🎜🎜🎜p-is-promise: 🎜rrreee🎜kindof: 🎜rrreee

7. Symbol.toStringTag 🎜🎜🎜원칙: Object.prototype.toString은 🎜🎜값을 읽습니다. 적용 가능한 시나리오: 사용자 정의 유형 필요🎜🎜참고: 호환성🎜 🎜rrreee

8. 대기 비교🎜🎜🎜원칙: 고정된 값으로 비교🎜🎜적용 가능한 시나리오: 정의되지 않음, , 문서 , null 등 🎜🎜🎜underscore.js: 🎜🎜🎜

요약🎜

생성자×
방법 th> 기본 데이터 유형 참조 유형 참고
유형 td> × NaN, 객체, document.all
√ 부분 재작성 가능
instanceof 여러 개의 창, 오른쪽 생성자 또는 클래스
isPrototypeof × td> null 및 정의되지 않음에 주의하세요
toString 내장된 프로토타입에 주의하세요
오리 유형 - 호환될 수 없습니다
Symbol.toString 태그 × 사용자 정의 개체 식별
etc. 비교 특수 개체

추가 식사: ES6의 향상된 NaN🎜

NaN 및 Number.NaN 기능

    🎜 🎜typeof 뒤에 숫자가 옵니다🎜🎜🎜🎜self가 자체와 동일하지 않습니다🎜🎜🎜🎜삭제 삭제할 수 없습니다🎜🎜🎜

    isNaN

    🎜🎜숫자가 아닌 경우 암시적 변환의 수신 결과가 NaN이면 true를 반환하고, 그렇지 않으면 false🎜를 반환합니다. 🎜rrreee

    Number.isNaN

    🎜🎜 값은 숫자이고 그 값이 NaN🎜🎜rrreee🎜기타 판단NaN의 메소드🎜rrreee

    indexOf 및 include

    🎜🎜indexOf는 검색할 수 없습니다NaN , includes는 🎜🎜rrreee🎜할 수 있습니다.[권장 학습: 🎜자바스크립트 고급 튜토리얼🎜]🎜

위 내용은 JavaScript는 데이터 유형을 어떻게 결정합니까? 공유하는 8가지 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 juejin.cn에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제