js循環(huán)中使用正則失效異常的踩坑實戰(zhàn)
1、異常案例:
使用正則匹配111
const regular = /111/g; // 匹配111 // console.log(regular.test('111')); // true 匹配成功 // console.log(regular.test('111,111')); // true 匹配成功 const list = [ '111', '111', '111,111', '111,111' ]; list.forEach((element, index) => { // 異常寫法 console.log('log_________' + regular.test(element)); }); // 打印結果 // log_________true // log_________false // 會存在正則匹配為false的異常 // log_________true // log_________true
發(fā)現了lastIndex 這個屬性。
2、原因分析
用正則表達式只要設置了全局匹配標志 /g ,test()方法 的執(zhí)行就會改變正則表達式 lastIndex 屬性。再循環(huán)中連續(xù)的執(zhí)行 test() 方法,后面的執(zhí)行將會從 lastIndex 數字處開始匹配字符串。
原來如此,看來test() 方法確實也不能隨便濫用。
確認驗證一下:
const regular = /111/g; // 匹配111 const list = [ '111', '111', '111,111', '111,111' ]; list.forEach((element, index) => { // 異常寫法 console.log('log_________' + regular.test(element)); // 打印lastIndex console.info('logLastIndex___' + regular.lastIndex); }); // 打印結果 // log_________true // logLastIndex___3 // log_________false // 確實因為lastIndex為3導致的 // logLastIndex___0 // log_________true // logLastIndex___3 // log_________true // logLastIndex___7
3、解決方法1
上面我們發(fā)現正則test()方法有l(wèi)astIndex屬性,每次循環(huán)給恢復一下。
const regular = /111/g; // 匹配111 const list = [ '111', '111', '111,111', '111,111' ]; list.forEach((element, index) => { regular.lastIndex = 0; console.log('log_________' + regular.test(element)); // 打印正常 });
問題解決 OK了。
3、解決方法2
上面我們發(fā)現正則表達式設置了全局標志 /g 的問題,去掉/g全局匹配。(這個具體還得看自己的應用場景是否需要/g)
const regular = /111/; // 去掉/g全局匹配 const list = [ '111', '111', '111,111', '111,111' ]; list.forEach((element, index) => { console.log('log_________' + regular.test(element)); // 打印正常 });
OK了。
3、解決方法3
js有基本數據類型和引用數據類型
ECMAScript包括兩個不同類型的值:基本數據類型和引用數據類型。\
基本數據類型:Number、String、Boolen、Undefined、Null、Symbol、Bigint。\
引用數據類型:也就是對象類型Object type,比如:對象(Object)、數組(Array)、函數(Function)、日期(Date)、正則表達式(RegExp)。
so正則表達式屬于引用數據類型,按傳統(tǒng)思維肯定是需要“深拷貝”的,需要new 一個新Object。
const regular = /111/g; const list = [ '111', '111', '111,111', '111,111' ]; list.forEach((element, index) => { // 正確寫法 new RegExp的內存指向在循環(huán)過程中每次都單獨開辟一個新的“對象”,不會和前幾次的循環(huán)regular.test(xxx)改變結果而混淆 // console.log('log_________' + /111/g.test(element)); // 這樣寫當然也行 console.log('log_________' + new RegExp(regular).test(element)); // 打印OK了 });
OK了。
總結
到此這篇關于js循環(huán)中使用正則失效異常的踩坑的文章就介紹到這了,更多相關js循環(huán)中正則失效異常內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
webpack 插件html-webpack-plugin的具體使用
本篇文章主要介紹了webpack 插件html-webpack-plugin的具體使用,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-04-04