# typeof 与 instanceof 的区别

xcooo

# 追问: 您判断数据类型用的哪个

  • typeof 只能判断简单的数据类型
  • 判断复杂数据类型 我用 Object.prototype.toString.call()
var arr = [];var arr2 = {};var arr3 = new Date();var arr4 = new RegExp();var arr5 = null;
  console.log( Object.prototype.toString.call(arr) == '[object Array]' ); //true
  console.log( Object.prototype.toString.call(arr2) == '[object Object]' ); //true
  console.log( Object.prototype.toString.call(arr3) == '[object Date]' ); //true
  console.log( Object.prototype.toString.call(arr4) == '[object RegExp]' ); //true
  console.log( Object.prototype.toString.call(arr5) == '[object Null]' ); //true
1
2
3
4
5
6
上次更新: 2020/10/12 下午2:13:19