typeof(array)===object和如何判断array & object 的问题

上篇留了个遗留问题 typeof([]) // object ,如果typeof将array返回的是object那我们要怎么判断,传进来的变量array和object呢?
下面来走进…JS。

type([])

JavaScript的数据结构中有提到
JS有7种数据类型

The latest ECMAScript standard defines seven data types:
Six data types that are primitives(原始类型):
Boolean
Null
Undefined
Number
String
Symbol (new in ECMAScript 6)
and Object(对象类型)

而typeof这个方法返回的是原始类型,或者object

1
2
3
4
5
6
7
8
9
Undefined	"undefined"
Null "object" (Null返回object比较特殊,是个历史遗留问题,这个不管它)
Boolean "boolean"
Number "number"
String "string"
Symbol (new in ECMAScript 2015) "symbol"
Host object (provided by the JS environment) Implementation-dependent
Function object (implements [[Call]] in ECMA-262 terms) "function"
Any other object "object"

为啥typeof(array)等于object也有了解释
Arrays are regular objects for which there is a particular relationship between integer-key-ed properties and the ‘length’ property. Additionally, arrays inherit from Array.prototype which provides to them a handful of convenient methods to manipulate arrays. For example, indexOf (searching a value in the array) or push (adding an element to the array), etc. This makes Arrays a perfect candidate to represent lists or sets.
array其实并不是JS标准的7种类型,只算是object的一种。

判断 Array Object

两种方法

  • Array.isArray (对老浏览器,可能有兼容性问题)
  • Object.prototype.toString.call()

好了,这篇就到这了,希望能让看客老爷有些收获,感谢阅读!