javascript中contains是否包含功能實(shí)現(xiàn)代碼(擴(kuò)展字符、數(shù)組、dom)
一個(gè)小誤區(qū) JS中的contains
今天想要用JS判斷集合中是否包含另一個(gè)集合。
發(fā)現(xiàn),Contains并不能達(dá)到所要的效果,查找之后發(fā)現(xiàn)了問題
原來(lái),js的contains方法用來(lái)查看dom元素的包含關(guān)系,并不是Java中數(shù)組的contains方法。
先看一下duyunchao同學(xué)分享的代碼
$(document).ready(function() {var Arrays = [’11’,’22’,’33’];var Array =’11’;if(Arrays.indexOf(Array) >= 0) {alert(’Arrays中包含Array’);}});
若js要判斷數(shù)組的包含關(guān)系,應(yīng)該用indexof
原生JS中是有contains方法的,但只有dom元素的包含關(guān)系,這里好吧啦網(wǎng)就為大家分享一下擴(kuò)展的字符string與數(shù)組arr的擴(kuò)展代碼
結(jié)構(gòu)與測(cè)試代碼如下
<div id='div1'><div id='div2'>jb51.net</div></div><script type='text/javascript'>var div1= document.getElementById('div1');var div2= document.getElementById('div2');console.log(div1.contains(div2));var str1='jb51.net';var str2='jb51';console.log(str1.contains(str2));</script>
但它并不是字符串方法,,僅用于判斷DOM元素的包含關(guān)系,參數(shù)是Element類型
若要在JS中判斷倆字符串的包含關(guān)系,用indexOf()
但是我們可以通過(guò)擴(kuò)展的方法來(lái)實(shí)現(xiàn)
<div id='div1'><div id='div2'>jb51.net</div></div><script type='text/javascript'>var div1= document.getElementById('div1');var div2= document.getElementById('div2');console.log('div1.contains(div2)='+div1.contains(div2));//字符擴(kuò)展contains就不會(huì)報(bào)錯(cuò)了String.prototype.contains = function(a) { return - 1 < this.indexOf(a)};var str1='jb51.net';var str2='jb51';console.log('str1.contains(str2)='+str1.contains(str2));//數(shù)組擴(kuò)展contains適用于數(shù)組判斷Array.prototype.contains = function(a) { if ('string' == typeof a || 'number' == typeof a) for (var b in this) if (a == this[b]) return ! 0; return ! 1};var arr1=['jb51.net','jbzj.com','jb51.com'];var str3='jb51.net';console.log('arr1.contains(str3)='+arr1.contains(str3));</script>
下面是運(yùn)行結(jié)果
所以后期我們的代碼可以加上這兩段即可
//字符擴(kuò)展contains就不會(huì)報(bào)錯(cuò)了String.prototype.contains = function(a) { return - 1 < this.indexOf(a)};//數(shù)組擴(kuò)展contains適用于數(shù)組判斷Array.prototype.contains = function(a) { if ('string' == typeof a || 'number' == typeof a) for (var b in this) if (a == this[b]) return ! 0; return ! 1};
以上就是javascript中contains是否包含功能實(shí)現(xiàn)代碼(擴(kuò)展字符、數(shù)組、dom)的詳細(xì)內(nèi)容,更多關(guān)于js contains的資料請(qǐng)關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. 什么是Python變量作用域2. Android 實(shí)現(xiàn)徹底退出自己APP 并殺掉所有相關(guān)的進(jìn)程3. Vue實(shí)現(xiàn)仿iPhone懸浮球的示例代碼4. js select支持手動(dòng)輸入功能實(shí)現(xiàn)代碼5. Android studio 解決logcat無(wú)過(guò)濾工具欄的操作6. vue使用moment如何將時(shí)間戳轉(zhuǎn)為標(biāo)準(zhǔn)日期時(shí)間格式7. bootstrap select2 動(dòng)態(tài)從后臺(tái)Ajax動(dòng)態(tài)獲取數(shù)據(jù)的代碼8. 一個(gè) 2 年 Android 開發(fā)者的 18 條忠告9. PHP正則表達(dá)式函數(shù)preg_replace用法實(shí)例分析10. vue-drag-chart 拖動(dòng)/縮放圖表組件的實(shí)例代碼
