1 typeof
我的第一反应是`typeof`。但是正中对方下怀。
typeof []
‘object’
这样返回的是`object`
这是一个JS很怪异的地方。
为什么很怪异的呢,因为小白往往以{}和[]区分Array和Object
但是如果你看JS的`Object`官方文档,typeof这样的行为或许有点道理
```\
All objects in JavaScript are descended from Object; all objects inherit methods and properties from Object.prototype
一切对象都继承了Object的属性和方法。
但是typeof还是很复杂的。typeof的文档是这么描述:
对于,基本类型Undefined,Boolean,Number,String这些基本类型及其基本包装类型,typeof的行为是正常的。
值得关注的是Null:
typeof null === 'object';
文档的解释是这样的:
In the first implementation of JavaScript, JavaScript values were represented as a type tag and a value. The type tag for objects was 0. null was represented as the NULL pointer (0x00 in most platforms). Consequently, null had 0 as type tag, hence the bogus typeof return value. (reference)
大意是:null代表一个空指针,和对象有相同的type tag:0, 这造成了typeof奇怪的返回值。
typeof Symbol是ES6推出的新的数据类型,返回值是symbol
。
typeof函数对象的返回值是function
typeof宿主对象(依赖于JS环境的对象)的返回值的独立的,并不意味着不返回object
typeof其他对象的返回值是object
,包括但不限于Array, Date, RegExp
那么应该用什么呢?
2 instanceof
第一种方法是:instanceof
> [] instanceof Array
true
这是es3的规定,但是这必须假定只有一个全局执行环境
第二种方法是:isArray
这是ES5的标准,被IE9+支持
> Array.isArray([])
true