判斷陣列的方法

2022-04-15 15:59:37 字數 2802 閱讀 5458

有以下 3 個判斷陣列的方法,請分別介紹它們之間的區別和優劣object.prototype.tostring.call() 、 instanceof 以及 array.isarray()

1. object.prototype.tostring.call()

const an = ['hello','an'];

an.tostring();

//"hello,an"

object.prototype.tostring.call(an); //

"[object array]"

這種方法對於所有基本的資料型別都能進行判斷,即使是 null 和 undefined 。

object.prototype.tostring.call('an') //

"[object string]"

object.prototype.tostring.call(1) //

"[object number]"

object.prototype.tostring.call(symbol(1)) //

"[object symbol]"

object.prototype.tostring.call(null) //

"[object null]"

object.prototype.tostring.call(undefined) //

"[object undefined]"

object.prototype.tostring.call(function(){}) //

"[object function]"

object.prototype.tostring.call() //

"[object object]"

object.prototype.tostring.call()常用於判斷瀏覽器內建物件時。

2. instanceof

instanceof的內部機制是通過判斷物件的原型鏈中是不是能找到型別的prototype

使用instanceof判斷乙個物件是否為陣列,instanceof會判斷這個物件的原型鏈上是否會找到對應的array的原型,找到返回true,否則返回false

instanceof array; //

true

instanceof只能用來判斷物件型別,原始型別不可以。並且所有物件型別 instanceof object 都是 true。

instanceof object; //

true

3. array.isarray()

var iframe = document.createelement('iframe');

xarray = window.frames[window.frames.length-1].array;

var arr = new xarray(1,2,3); //

[1,2,3]

//correctly checking for array

array.isarray(arr); //

true

object.prototype.tostring.call(arr); //

true

//considered harmful, because doesn't work though iframes

arr instanceof array; //

false

array.isarray()object.prototype.tostring.call()

array.isarray()是es5新增的方法,當不存在array.isarray(),可以用object.prototype.tostring.call()實現。

if (!array.isarray) ;

}

其他觀點:

這裡感覺不太清晰。事實上應該不是改變 tostring 的上下文,而是改變呼叫的 tostring 方法:

const arr = [1, 2]

arr.tostring === object.prototype.tostring //

false, 所以兩者不同,實際上陣列上重寫了 tostring 方法

const o =

o.tostring === object.prototype.tostring //

true, 所以物件預設不需要如此呼叫。但如果將物件的方法改寫就不一定了

o.tostring = function

changedtostring()

o.tostring()

//'haha'

object.prototype.tostring.call(o) //

'[object object]'. 發現 object.prototype.tostring 也是可以被改寫的...

call方法的第乙個引數會被當作this,所以arr.tostring()object.prototype.tostring.call(arr)並沒有改變this,而是改變了呼叫的函式。

判斷陣列的方法

這麼基礎的東西實在不應該再記錄了,不過嘛,溫故知新 就先從資料型別開始吧 js六大資料型別 number string object boolean null undefined string 由單引號或雙引號來說明,如 string number 什麼整數啊浮點數啊都叫數字,boolean 就是t...

JS陣列判斷,方法

怎麼判斷乙個物件是不是陣列?首先可以用 es5 提供的 isarray 方法進行判斷 注意 array.isarray是es 5.1推出的,不支援ie6 8,所以在使用的時候也應注意相容問題。可以使用 instanceof array 來判斷,不過這種方式存在問題,比如當存在多個全域性物件 如使用i...

js中判斷陣列的方法

首先宣告乙個陣列var arr js中typeof只能檢測簡單資料型別 如果typeof arr,會返回object,顯然不能判斷到底是不是乙個陣列 那麼js中用什麼方法檢測陣列呢?方法1 isarray 方法 array.isarray arr 但是這個方法有相容性 ie瀏覽器只有ie9以上才支援...