我的正则表达式与条件语句不匹配
谁能告诉我为什么即使我的警报显示我的正则表达式字符串匹配,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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
.match()
的返回值不是字符串,而是字符串数组。当数组碰巧包含相同的值时,它们不会被比较为相等。Try
也许还应该验证返回值也不为空:
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
Probably should also verify that the return values aren't null too:
您的 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].你有没有尝试过:
Have you tried: