1. 程式人生 > >前端面試紀實(四):如何判斷一個變數是陣列:typeof和instanceof

前端面試紀實(四):如何判斷一個變數是陣列:typeof和instanceof

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