1. 程式人生 > 程式設計 >利用JS判斷元素是否為陣列的方法示例

利用JS判斷元素是否為陣列的方法示例

此處提供可供驗證的資料型別

let a = [1,2,3,4,5,6];
 let b = [
 {name: '張飛',type: 'tank'},{name: '關羽',type: 'soldier'},{name: '劉備',type: 'shooter'},];
 let c = 123;
 let d = 'www';
 let e = {name: '安琪拉',type: 'mage'};

1.通過Array.isArray()

Array.isArray()能判斷一個元素是否為陣列,如果是就返回true,否則就返回false

console.log(Array.isArray(a)); // true
 console.log(Array.isArray(b)); // true
 console.log(Array.isArray(c)); // false
 console.log(Array.isArray(d)); // false
 console.log(Array.isArray(e)); // false

2.通過instanceof判斷

instanceof運算子用於檢測某個例項是否屬於某個物件原型鏈中

console.log(a instanceof Array); // true
 console.log(b instanceof Array); // true
 console.log(c instanceof Array); // false
 console.log(d instanceof Array); // false
 console.log(e instanceof Array); // false

還可以用於判斷物件

console.log(e instanceof Object); // true

判斷是否為陣列就是檢測Arrray.prototype屬性是否存在於變數陣列(a,b)的原型鏈上,顯然a,b為陣列,擁有Arrray.prototype屬性,所以為true

3.通過物件建構函式的constructor判斷

Obiect的每個例項都有建構函式constructor,儲存著建立每個物件的函式

利用JS判斷元素是否為陣列的方法示例

console.log(a.constructor === Array); // true
console.log(b.constructor === Array); // true

以下包含判斷其它的資料型別驗證

console.log(c.constructor === Number); // true
console.log(d.constructor === String); // true
console.log(e.constructor === Object); // true

4.通過Object.prototype.toString.call()判斷

通過原型鏈查詢呼叫

console.log(Object.prototype.toString.call(a) === '[object Array]'); // true
console.log(Object.prototype.toString.call(b) === '[object Array]'); // true

以下包含判斷其它的資料型別驗證

console.log(Object.prototype.toString.call(c) === '[object Number]'); // true
console.log(Object.prototype.toString.call(d) === '[object String]'); // true
console.log(Object.prototype.toString.call(e) === '[object Object]'); // true

5.通過物件原型鏈上的isPrototypeOf()判斷

Array.prototype屬性為Array的建構函式原型,裡面包含有一個方法 isPrototypeOf() 用於測試一個物件是否存在於;另一個物件的原型鏈上。

console.log(Array.prototype.isPrototypeOf(a)); // true
 console.log(Array.prototype.isPrototypeOf(b)); // true
 console.log(Array.prototype.isPrototypeOf(c)); // false
 console.log(Array.prototype.isPrototypeOf(d)); // false
 console.log(Array.prototype.isPrototypeOf(e)); // false

總結

到此這篇關於利用JS判斷元素是否為陣列的文章就介紹到這了,更多相關JS判斷元素為陣列內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!