在Javascript中比较两个正则表达式并获得奇怪的结果

时间:2016-10-07 06:59:38

标签: javascript

有人可以在Javascript中解释这种奇怪的行为吗?当我使用return foo(x-1)方法进行比较时,我没有得到预期的结果。

match()

3 个答案:

答案 0 :(得分:1)

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")}  




答案 1 :(得分:1)

匹配返回一系列匹配项:

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

在比较两个阵列时,您的第一次评估将始终失败。

这是您尝试实现目标的正确方法。

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

虽然如果你想真正使用正则表达式检查第一个字母,我不会推荐它。对于太微不足道的事情来说太多的开销(只是我的两分钱)。

玩得开心! :)

答案 2 :(得分:1)

在以下几行代码中,您检查变量mat_1mat_2是否两个单词都以'w'开头,btw 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");
}