我的正则表达式与条件语句不匹配

发布于 2024-09-27 14:43:06 字数 522 浏览 0 评论 0原文

谁能告诉我为什么即使我的警报显示我的正则表达式字符串匹配,if 语句也不会被触发?我下面有示例代码。提前致谢。

$(document).ready(function () {
    $('div#primaryNavigation').find('a').each(function () {
        var pattern = /my-link1|my-link2|my-link3|my-link4/;
        var myWindow = window.location.pathname.match(pattern);
        var href = $(this).attr('href').match(pattern);
        alert('Show link and href until match: ' + myWindow + ' ' + href);
        if (myWindow == href) {
            //* Do Something *
        };
    });
});

Can anyone tell me why, even when my alert shows that my regular expression strings match, the if statement is not triggered? I have sample code below. Thanks in advance.

$(document).ready(function () {
    $('div#primaryNavigation').find('a').each(function () {
        var pattern = /my-link1|my-link2|my-link3|my-link4/;
        var myWindow = window.location.pathname.match(pattern);
        var href = $(this).attr('href').match(pattern);
        alert('Show link and href until match: ' + myWindow + ' ' + href);
        if (myWindow == href) {
            //* Do Something *
        };
    });
});

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

静待花开 2024-10-04 14:43:06

.match() 的返回值不是字符串,而是字符串数组。当数组碰巧包含相同的值时,它们不会被比较为相等。

Try

if (myWindow[0] == href[0]) { ... }

也许还应该验证返回值也不为空:

if (myWindow && href && myWindow[0] === href[0]) { ... }

The return value from .match() is not a string, it's an array of strings. Arrays don't compare as equal when they happen to contain the same values.

Try

if (myWindow[0] == href[0]) { ... }

Probably should also verify that the return values aren't null too:

if (myWindow && href && myWindow[0] === href[0]) { ... }
楠木可依 2024-10-04 14:43:06

您的 if 语句失败的原因与 [1,2,3] == [1,2,3] 失败的原因相同。您需要比较每个列表的内容,或者更简单地比较 myWindow[0] == href[0]。

Your if statement fails for the same reason [1,2,3] == [1,2,3] fails. You need to compare the contents of each list, or more simply compare myWindow[0] == href[0].

魄砕の薆 2024-10-04 14:43:06

你有没有尝试过:

var pattern =/(my-link1|my-link2|my-link3|my-link4)/;

Have you tried:

var pattern =/(my-link1|my-link2|my-link3|my-link4)/;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文