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

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

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

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

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

1.通過Array.isArray()

Array.isArray()能判斷一個(gè)元素是否為數(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運(yùn)算符用于檢測(cè)某個(gè)實(shí)例是否屬于某個(gè)對(duì)象原型鏈中

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

還可以用于判斷對(duì)象

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

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

3.通過對(duì)象構(gòu)造函數(shù)的constructor判斷

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

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

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

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ù)類型驗(yàn)證

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.通過對(duì)象原型鏈上的isPrototypeOf()判斷

Array.prototype屬性為Array的構(gòu)造函數(shù)原型,里面包含有一個(gè)方法 isPrototypeOf() 用于測(cè)試一個(gè)對(duì)象是否存在于;另一個(gè)對(duì)象的原型鏈上。

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

總結(jié)

到此這篇關(guān)于利用JS判斷元素是否為數(shù)組的文章就介紹到這了,更多相關(guān)JS判斷元素為數(shù)組內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論