简体   繁体   English

jQuery grep跳过数组中的术语

[英]jQuery grep is skipping terms in array

I am trying to filter an array of strings using the jQuery grep function, but it is skipping the elements in the array. 我正在尝试使用jQuery grep函数过滤字符串数组,但它正在跳过数组中的元素。 If I debug through the code all the conditions are returning true, but if I run the code without debugging it is skipping the second element. 如果我通过代码调试所有条件都返回true,但是如果我在不调试的情况下运行代码,则会跳过第二个元素。

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery.grep demo</title>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<p></p>
<script>
var arr = [ { value : "A1-99-101"}, { value : "A1-99-102"}, { value : "A1-99-109" } ];
var regex = /(?=.*?\bA1.*\b).*/ig;
var newarr = jQuery.grep(arr, function( n, i ) {
return (regex.test(n.value));
});
var printarr = '';
for (var i = 0; i < newarr.length; ++i) {
  printarr += newarr[i].value + ',';
}
$( "p" ).text( printarr );
</script>
</body>
</html>

You have an issue because of g modified in your regexp ( .../ig ). 由于在正则表达式( .../ig )中修改了g ,因此您遇到了问题。 It forces regular expression to continue from last matched position. 它强制正则表达式从最后匹配的位置继续。 Here is what is happening: 这是正在发生的事情:

  • regexp matches to A1-99-101 and saves position at 0 regexp匹配A1-99-101并将位置保存为0
  • next iteration it moves position to 1, but doesn't match A1-99-102 下一次迭代将位置移至1,但与A1-99-102不匹配
  • then regexp resets itself, because it reached end of the string 然后regexp重置自身,因为它到达了字符串的结尾
  • and at last it matches third element A1-99-109 最后匹配第三个元素A1-99-109

To fix this just remove g modifier: 要解决此问题,只需删除g修饰符:

var regex = /(?=.*?\bA1.*\b).*/i;

Also here is link to fiddle with working code . 另外这里是链接到工作代码

Edit 编辑

Also your regexp looks too complicated to me. 您的正则表达式对我来说也看起来太复杂了。 If you just want to filter strings starting with A1 , then use following regexp: 如果您只想过滤以A1开头的字符串,请使用以下regexp:

var regex = /A1/i;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM