js 判斷確切判斷Array和Object

2022-07-16 08:27:10 字數 643 閱讀 5642

js的陣列其實是特殊的物件。

這就導致:

typeof [1,2,3] === 'object'

[1,2,3] instanceof object  和 [1,2,3] instanceof array 都是true

但是注意 [1,2,3]  !=  , [1,2,3] != [1,2,3] 。因為物件之間的 == 與 ===是一樣的。

那麼要確切判斷的話,經過我試驗,可以使用以下規則:

.__proto__ === array.prototype

{}.__proto__ === object.prototype

附帶2個物件深拷貝方法。工程裡的copy1和我寫的copy2.當然copy2 在規模大點的時候,效率比copy1要高。

function

copy1(obj)

else

returno;}

function

copy2(obj);

for(var key in

obj)

}else

if(obj.__proto__ ===array.prototype)

}else

return

re;}

js判斷Array和object的區別

第一步先排除typeof方法 typeof判斷不能區分array和object,用typeof檢測到兩種資料型別都是object 接下來看其他幾種可用的方法 1 instanceof方法,instanceof 的使用方法是左右兩邊各有乙個物件,如下圖所示 左邊的arr是我們待測的子物件arr,右邊是...

js如何判斷陣列是Array型別

在說明如何判斷乙個物件為陣列型別前,我們先鞏固下js的資料型別,js一共有六大資料型別 number string object boolean null undefined。var str string console.log typeof str string var num 1 console...

js如何判斷陣列是Array型別

在說明如何判斷乙個物件為陣列型別前,我們先鞏固下js的資料型別,js一共有六大資料型別 number string object boolean null undefined。var str string console.log typeof str string var num 1 console...