JavaScript类型判断 和通用方法

56 阅读1分钟

在JavaScript中,我们经常需要判断一个变量或一个值的数据类型,以便进行相应的操作或处理。JavaScript提供了多种类型判断的方法,但是它们各有优劣,不同的场景需要选择合适的方法。本文将介绍JS类型判断的三种常用方法:typeof、instanceof和Object.prototype.toString,并分析它们的原理和适用范围。

typeof 1 // "number"  
typeof "hello" // "string"  
typeof true // "boolean"  
typeof undefined // "undefined"  
typeof null // "object"  
typeof {} // "object"  
typeof [] // "object"  
typeof Symbol() // "symbol"  

[] instanceof Array // true  
[] instanceof Object // true  
{} instanceof Object // true  
new Date() instanceof Date // true  
function a() {}  
a instanceof Function // true  
new a() instanceof a // true  

Object.prototype.toString.call(1) // "[object Number]"  
Object.prototype.toString.call("hello") // "[object String]"  
Object.prototype.toString.call(true) // "[object Boolean]"  
Object.prototype.toString.call(undefined) // "[object Undefined]"  
Object.prototype.toString.call(null) // "[object Null]"  
Object.prototype.toString.call({}) // "[object Object]"  
Object.prototype.toString.call([]) // "[object Array]"  
Object.prototype.toString.call({}) // "[object Object]"
Object.prototype.toString.call(function(){}) // "[object Function]"

Array.isArray([]) // true
Array.isArray({}) // false

总结

function getType(obj) {
  const type = typeof obj;
  
  if (type !== "object") {
    return type;
  }
  
  if (Array.isArray(obj)) {
    return "array";
  }
  
  if (obj === null) {
    return "null";
  }
  
  return Object.prototype.toString.call(obj).slice(8, -1).toLowerCase();
}

console.log(getType("hello")); // 输出: "string"
console.log(getType(123)); // 输出: "number"
console.log(getType([1, 2, 3])); // 输出: "array"
console.log(getType({ name: "Tom", age: 18 })); // 输出: "object"
console.log(getType(null)); // 输出: "null"
console.log(getType(undefined)); // 输出: "undefined"