const handlePage = (page) => {
const reg = new RegExp(`${page}_`, "g");
return (action) => {
if(!reg.test(action.type)){
return "error";
}
return "success";
}
}
const pageBack = handlePage("auth");
今天在写react的时候,写了类似于上面这样一段代码来封装action,结果发现当action.type是以${page}_开头时,也只是在奇数次的时候返回了success。
pageBack({ type: "auth_login" }) // success
pageBack({ type: "auth_loginout" }) // error
pageBack({ type: "auth_register" }) // success
pageBack({ type: "auth_reset" }) // error
找了很久才发现是由于RegExp创建的地方不对,最后改成如下形式:
const handlePage = (page) => {
return (action) => {
const reg = new RegExp(`${page}_`, "g");
if(!reg.test(action.type)){
return "error";
}
return "success";
}
}
const pageBack = handlePage("auth");
pageBack({ type: "auth_login" }) // success
pageBack({ type: "auth_loginout" }) // success
pageBack({ type: "auth_register" }) // success
pageBack({ type: "auth_reset" }) // success
为什么两种写法结果不一样呢,这是因为每个RegExp都有一个lastIndex属性,当使用test方法且全局匹配时(g),如果能匹配到结果,则返回true,且lastIndex会改变,下一次再调用test方法时,会从lastIndex指定的位置处开始检索;如果不能匹配到结果,则返回false,且lastIndex属性置0
var reg1 = /^test/g;
reg1.test("test11"); // true
reg1.lastIndex // 4
reg1.test("test22") // false
reg1.lastIndex // 0
var reg2 = /^test/;
reg2.test("test11"); // true
reg2.lastIndex // 0
reg2.test("test22") // true
如果不是全局匹配,则每次调用test方法时,lastIndex都是0,即每次都是从字符串最开始位置进行匹配查找。