Jquery教程
Jquery动效
Jquery HTML/CSS
Jquery 事件
jquery常用

Jquery grep()方法

jQuery grep()方法

jQuery 查找满足给定过滤器功能的数组元素。它不会影响原始数组。此方法返回过滤后的数组,即满足给定过滤器功能的元素。

语法

grep() 的常用语法/strong>方法如下:
jQuery.grep(array, function(element, index) [, invert])

参数值

此方法包括一些定义如下的参数。
数组: 是强制性参数。它指定了要搜索的类似数组的对象。
function(element,index): : 这指定了用作过滤器函数的函数。它接受两个名为 element index 的参数,其中第一个参数包含数组元素,第二个参数包含数组元素参数保存相应元素的索引。它返回一个布尔值, true false 。它也是必需参数。此函数处理每个数组元素。如果元素通过条件,则只有该元素才会包含在结果中。
invert: 是一个可选参数。它接受布尔值。其默认值为 false 。如果将其指定为false或未传递,则 grep()函数将返回过滤器函数为其返回 true 的数组元素。如果将此参数指定为 true ,则 grep()函数将返回其过滤器函数返回false的数组元素。
现在,让我们来看一下一些使用 grep()方法的示例。

Example1

在此示例中,有一个名为 的数组arr ,其中包含一些项目。我们正在此数组上应用 grep()方法,而不指定其可选的 invert 参数。因此,该方法返回的索引可以完全被2整除的数组元素,其索引大于或等于2。
<!DOCTYPE html>
<html>
<head>
<title> jQuery grep() method </title>
<script src = "/ajax/libs/jquery/3.5.1/jquery.min.js"> </script>
</head>
<body>
<h4> This is an example of using the grep() method. </h4>
<p> Click the following button to see the effect. </p>
<button id = "btn"> Click me </button>
<p id = "p1"> </p>
<p id = "p2"> </p>
<script>
$(document).ready(function() {
$("#btn").click(function(){
var arr = [ 12, 20, 60, 43, 56, 41, 60, 19, 42, 60, 78, 18];
$("#p1").html("Array elements before applying the <b> grep() </b> method: " + arr + "<br>");
arr = $.grep(arr, function(element, index) {
return ( element%2 == 0 && index >= 2 );
});
$("#p2").html("Array elements after applying the <b> grep() </b> method: " + arr);
});
});
</script>
</body>
</html>
输出
执行上述代码后,输出将为-
jQuery grep()方法
单击给定的按钮后,输出为-
jQuery grep()method

Example2

在此示例中,我们使用 invert 参数并进行设置改为 true 。在这里,有一个名为 arr 的数组,其中包含一些项目。如果未将 invert 参数设置为true,则该函数将返回不等于60的数组元素。但是由于我们正在使用 invert 参数并将其设置为< strong> true ,因此该函数返回值为 60的数组元素。
在输出中,我们可以看到 grep()方法返回指定过滤器函数返回false的数组元素。
<!DOCTYPE html>
<html>
<head>
<title> jQuery grep() method </title>
<script src = "/ajax/libs/jquery/3.5.1/jquery.min.js"> </script>
</head>
<body>
<h4> This is an example of using the grep() method. </h4>
<p> Click the following button to see the effect. </p>
<button id = "btn"> Click me </button>
<p id = "p1"> </p>
<p id = "p2"> </p>
<script>
$(document).ready(function() {
$("#btn").click(function(){
var arr = [ 12, 20, 60, 44, 56, 41, 60, 19, 42,];
$("#p1").html("Array elements before applying the <b> grep() </b> method: " + arr + "<br>");
arr = $.grep(arr, function(element, index) {
return ( element != 60);
}, true);
$("#p2").html("Array elements after applying the <b> grep() </b> method: " + arr);
});
});
</script>
</body>
</html>
输出
执行上述代码后,输出为-
jQuery grep()方法
单击给定按钮时,输出为-
jQuery grep()方法
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4