RegExp 对象方法 exec()
const arr=['ezlost', 'losthome', 'meller' , 'cool', 'eat']
let pett = /e/g
arr.forEach(function(a){
console.log(pett.exec(a))
})
运行结果
const arr=['ezlost', 'losthome', 'meller' , 'cool', 'eat']
let pett = /e/g
arr.forEach(function(a){
console.log(pett.exec(a))
})
["e", index: 0, input: "ezlost", groups: undefined]
["e", index: 7, input: "losthome", groups: undefined]
null
null
["e", index: 0, input: "eat", groups: undefined]
显而易见其中'meller'没有被识别,但这是为什么呢?
【其实exec()方法在执行完会将pett的lastIndex指向当前位置的下一位】
arr.forEach(function(a){
console.log(pett.exec(a));console.log(pett.lastIndex)
})
["e", index: 0, input: "ezlost", groups: undefined]
1
["e", index: 7, input: "losthome", groups: undefined]
8
null
0
null
0
["e", index: 0, input: "eat", groups: undefined]
1
由上运行结果可得出:当运行到losthome时,‘e’的位置是7,这时pett.lastIndex就指向了8,所以会出现null的现象。
这里有一个个人的解决方案,就是将‘let pett = /e/g’ 的全局去掉
let pett = /e/ ,就会正常或者使用match
const arr1=['ezlost', 'losthome', 'meller' , 'cool', 'eat']
let pett1 = /e/
arr1.forEach(function(a){
let b = pett1.exec(a)
console.log(b)
console.log(pett1.lastIndex)
})
["e", index: 0, input: "ezlost", groups: undefined]
0
["e", index: 7, input: "losthome", groups: undefined]
0
["e", index: 1, input: "meller", groups: undefined]
0
null
0
["e", index: 0, input: "eat", groups: undefined]
0
[欢迎点评交流,如果有好的方法欢迎留言互相学习]