typeof
- 可以识别出基本类型String,、Number、Boolean、Undefined、Symbol
- 不能识别null
- 不能识别引用数据类型,会把null、array、object统一归为object类型
- 可以识别出function。
console.log(typeof 123) // number
instanceof
- 不能识别出基本的数据类型 String,、Number、Boolean、Undefined、Null、Symbol
- 可以检测出引用类型,array、object、function
console.log([1,2,3] instanceof Array) // true
constructor
- 在JavaScript中,每个对象都有一个constructor属性,它指向创建该对象的构造函数。通过对象的constructor属性,我们可以获取对象的构造函数,进而推断出对象的数据类型。
- 对于基本数据类型(如字符串、数字、布尔值),它们是没有 constructor 属性的,因此不能很好地识别出基本数据类型
console.log([1,2,3].constructor === Array) // true
Object.prototype.toString.call()
- 可以识别出所有的数据类型,并且返回类型的字符串标识
console.log(Object.prototype.toString.call( 1 )); // [object Number]
一般基本的类型可以选择typeof,引用类型可以使用instanceof