比较Javascript中的两个正则表达式,得到奇怪的结果

Comparing two regex in Javascript and getting weird results

本文关键字:正则表达式 结果 Javascript 比较 两个      更新时间:2023-09-26

谁能解释一下这个奇怪的行为在Javascript?当我使用match()方法进行比较时,我没有得到预期的结果。

var mat_1 = "wpawn";
var mat_2 = "wRook";
//compare both; do they have the same first letter? 
alert(mat_1.match(/^'w/) + " seems equal to " + mat_2.match(/^'w/));
if (mat_1.match(/^'w/) === mat_2.match(/^'w/)) {
    alert("They are really equal")
}
//another approach
if (mat_1[0] === mat_2[0]) {
    alert("Yes! Equals")
} 

match生成一个数组。您实际上应该使用数组比较函数,但为了简单演示,请尝试以下操作——选择并比较第一个匹配值。触发所有3个警报:

var mat_1 = "wpawn";
var mat_2 = "wRook";
//compare both; do they have the same first letter? 
alert(mat_1.match(/^'w/)+" seems equal to "+mat_2.match(/^'w/));
if(mat_1.match(/^'w/)[0] === mat_2.match(/^'w/)[0]){alert("They are really equal")}
//another approach
if(mat_1[0] === mat_2[0]){alert("Yes! Equals")}  

Match返回一个匹配数组:

String.prototype.match(pattern: Regex): Array<string>

在比较两个数组时,第一次求值总是会失败。

这是你想要达到的目标的正确方法。

'myWord'.match(/^'w/)[0] == 'mIsTeRy'.match(/^'w/)[0]

如果你真的想用正则表达式来检查第一个字母,我不建议你这么做。琐碎的事情却要花费太多的开销(只是我的两点意见)。

祝你编码愉快!:)

在接下来的代码行中,您正在检查变量mat_1mat_2是否两个单词都以'w'开头,顺便说一句,match()返回一个数组

if (mat_1.match(/^'w/) === mat_2.match(/^'w/)) {
    alert("They are really equal")
}

你可以试试

if (["w"] === ["w"]) {
    console.log("seems equal");
} else {
    console.log("not equal");
}

对于数组比较,您可以检查post

你要做的是

if (["w"][0] === ["w"][0]) { // match for the elements in the array
    console.log("seems equal");
} else {
    console.log("not equal");
}