RegExp.test()和RegExp.lastIndex
首先感謝同學幫助分析問題,最終才找到問題。
話不多說,直接上代碼說問題
- 第一版代碼
const result = parent.filter((child: ITree): boolean =>{
console.log(reg.test(child.name) || reg.test(child.id));
return reg.test(child.name) || reg.test(child.id);
})
console.log(result);
// 輸出結果
// true
// true
// [{...}]
- 第二版代碼
const result = parent.filter((child: ITree): boolean =>{
const isMatch = reg.test(child.name) || reg.test(child.id)
console.log(isMatch);
return isMatch;
})
console.log(result);
// 輸出結果
// true
// false
// [{...}]
正是這微妙的變化,導致找了半天的問題愣是沒找出來。
後查mdn發現有這麼一句描述
. 如果正則表達式設置了全局標誌,test() 的執行會改變正則表達式 lastIndex屬性。連續的執行test()方法,後續的執行將會從 lastIndex 處開始匹配字符串,(exec() 同樣改變正則本身的 lastIndex屬性值).
那這就是問題所在了,每次test()都會改變下一次的匹配開始位置,怪不得後面的匹配結果是false。
本來以爲這是個常用的test()方法,放心大膽的就用了,沒想到這個方法還有這麼一手!
所以學習方法的時候要全面瞭解一下,遇到方法出問題了就先去查查文檔,免得用錯了還毫不知情,找來找去浪費太多時間。