欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

利用JS判斷元素是否為數(shù)組的方法示例

 更新時間:2021年01月08日 16:05:32   作者:Fahrenheitzz  
這篇文章主要給大家介紹了關于利用JS判斷元素是否為數(shù)組的相關資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧

此處提供可供驗證的數(shù)據(jù)類型

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()能判斷一個元素是否為數(shù)組,如果是就返回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

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

3.通過對象構造函數(shù)的constructor判斷

Obiect的每個實例都有構造函數(shù)constructor,保存著創(chuàng)建每個對象的函數(shù)

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

以下包含判斷其它的數(shù)據(jù)類型驗證

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

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

通過原型鏈查找調(diào)用

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

以下包含判斷其它的數(shù)據(jù)類型驗證

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的構造函數(shù)原型,里面包含有一個方法 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判斷元素是否為數(shù)組的文章就介紹到這了,更多相關JS判斷元素為數(shù)組內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

最新評論