Object.prototype.toString.call():妙用

Object.prototype.toString.call() 方法是一种常用的方式来获取一个对象的确切类型。

function isArray(value) {

return Object.prototype.toString.call(value) === 'object Array';

}

console.log(isArray(\[\])); // 输出:true

console.log(isArray({})); // 输出:false

console.log(isArray('string')); // 输出:false

console.log(isArray(123)); // 输出:false

  • 对于数组:[object Array]
  • 对于日期:[object Date]
  • 对于正则表达式:[object RegExp]
  • 对于函数:[object Function]
  • 对于普通对象:[object Object]
  • 对于null:[object Null](尽管实际上返回的是[object Object],因为null不是一个对象)
  • 对于undefined:抛出TypeError(因为不能调用方法在undefined上)