typeof 类型判断
typeof 判断只能 JavaScript 中的基本类型和 Object 引用类型, 对于各种 Object 只是粗略的判断为 Object 类型, 并不会判断出对象的具体类型。所以 typeof 能判断的类型有 Number, String, Boolean, Symbol, undefined,BigInt,Object.

注: typefo null 的结果为 Object 类型的, 但实际上 null 并不是 Object类型, 它所以 Null 类型,能的到这样的结果是因为 JavaSscript typeof行为上的错误所导致的。

// 1. typeof

let symbol = Symbol()

typeof 23                       // number
typeof "Jason"                  // string
typeof true                     // boolean
typeof undefined                // undefined 
typeof symbol                   // symbol
typeof 9007199254740991n        // bigint


// 不判断对象的具体类型
typeof {}               // object
typeof []               // object
typeof new Error()      // object
typeof null             // object

typeof function(){}     // function
注: function 函数隶属于 Object 类型的 但是 typeof function 时返回的是 function 而并不是 Object,这是因为 typefo 对于 function 函数区分对待,实际不并不存在 function 类型, 这是 JavaSscript 早期的错误,但对编程非常便利。
instanceof 类型判断
instanceof 判断对象的具体类型, instanceof 是通过目标对象中原型链的 prototype 与指定类型的 prototype 进行类型检查, 只要原型链中存在指定类型的原型 prototype 就返回 true 反之 false, instanceof 没有 typeof 那么局限, 它可以对 Object 的各类对象进行具体的检查判断。
new Date() instanceof Date                              // true
new String() instanceof String                          // true
new Number() instanceof Number                          // true
new Error() instanceof Error                            // true
function(){} instanceof Function                        // true
new Map() instanceof Map                                // true
new Set() instanceof Set                                // true
new RegExp('ab+c', 'i') instanceof RegExps              // true

....
注: null 没有原型, 所以不可用此方法进行判断
Object.prototype.toString() 类型判断
各种类型或对象调用 Object.prototype.toString() 方法时将返回 [object 类型] 的字符串, 可以用来判断各种数据类型。只是返回的的字符串可能在实际的编程应用中有点不好操作, 所以需要一函数来对判断后返回的结果进行处理。
  let res= {}

  "Null Undefined String Number Boolean Function Date RegExp Error Array Object Math Class".split(" ").map(item =>{
    res["[object "+ item + "]"] = item.toLowerCase();
  })
  
    function  type(obj){
    return typeof obj === "object" || typeof obj === "function" ? res[Object.prototype.toString.call(obj)] || "object" : typeof obj;
  }
  
  // 测试
  let date = new Date();
  function f(){}
  
  
  type(date);       // date
  type(f);          // function
  type([])          // array

sheep
5 声望0 粉丝