前端面试题库

JS 有哪些数据类型,如何判断数据类型

数据类型更新时间:2024-08-26 14:58:14

答案

数据类型
  1. 基本数据类型: stringnumberbooleanundefinednullSymbolBigInt
  2. 引用类型: ObjectArrayFunctionDate
判断数据类型
  • tyepof: 返回变量数据类型的字符串

    typeof "abc"; // 'string' typeof 1; // 'number' typeof true; // 'boolean' typeof undefined; // 'undefined' typeof null; // 'object' typeof Symbol(); // 'symbol' typeof function() {}; // 'function' typeof {}; // 'object' typeof [1, 2]; // 'object' typeof new Date(); // 'object'
    1. 判断基本类型时,除了null返回'object'外、其他都会返回对应的数据类型字符串;

    2. 判断引用类型时,除了函数返回function,其他都返回object

    typeof不能区分引用类型,可以使用instanceOf来判断

  • instanceof: 判断构造函数的prototype是否在指定对象的原型上

    const obj = {} obj instanceof Object; // true function Person(){} const man = new Person(); man instanceof Person; // true
    1. instanceof返回一个布尔值
    2. 用来判断引用类型
  • Object.prototype.toString.call()

    toString()是 Object 的原型方法,调用时返回对象的[obejct type],其中type是对象的类型;

    const toString = Object.prototype.toString; toString.call("abc") // '[object String]' toString.call(1); // '[object Number]' toString.call(true); // '[object Boolean]' toString.call(null); // '[object Null]' toString.call(undefined); // '[object Undefined]' toString.call(Symbol()); // '[object Symbol]' toString.call(function() {}); // '[object Function]' toString.call({}); // '[object Object]' toString.call([]); // '[object Array]' toString.call(new Date()); // '[object Date]' toString.call(document); // '[object Document]' toString.call(window); // '[object Window]'

评论