我正在查看一些代码并找到第一行。当我发现如果我试图以语义保持不变的方式使它更简单时,我开始感到困惑,它不一样,结果也会改变。任何人都可以向我解释这种行为吗?
RegExp("\x3c").test(function(){return"\x3c"}) //false
RegExp("<").test(function(){return"<"}) //true
RegExp("\x3c").test("\x3c") //true
RegExp("<").test("<") //true
将非字符串传递给.test
时,它会转换为字符串,而不替换函数代码中的任何文字字符。查看前两个函数的字符串化版本:
console.log(function(){return"\x3c"}.toString());
console.log(function(){return"<"}.toString());
因为第一个函数的源有"\x3c"
,所以字符串化版本也包括 - "\x3c"
不会被'<'
取代。虽然"\x3c" === '<'
,解释器在字符串化函数时不会替代你。
当你将"\x3c"
传递给new RegExp
时(或任何函数,例如第三次测试),它将变成'<'
:
console.log("\x3c");
console.log(RegExp("\x3c"));
所以,你的原始代码相当于:
/</.test(String.raw`function(){return"\x3c"}`); //false
/</.test(String.raw`function(){return"<"}`); //true
/</.test("<"); //true
/</.test("<"); //true
test将字符串作为参数作为默认值,任何其他类型都将转换为字符串
const a = function(val) {
return val
}
console.log(a)
const res = RegExp("\x3c").test(a) //false
const res2 = RegExp("<").test(a) //false
console.log(res, res2)
const b = function() {
return "<"
}
const res3 = RegExp("<").test(b)
console.log(res3) //true
结果false
两个原因“function(val){return val}”不包含任何匹配项
res3
是真的因为"function(){return '<'}"
匹配"<"