Home > Web Front-end > JS Tutorial > body text

jquery数组过滤筛选方法grep()简介_jquery

WBOY
Release: 2016-05-16 16:45:35
Original
1485 people have browsed it

jquery中有个grep()方法用于数组元素过滤筛选,悲剧的是,平时我们用的api文档中找不到这个说明。查看官方说明:http://api.jquery.com/jQuery.grep/


grep()的使用方法:

grep(array,callback,invert)

array:待过滤数组;

callback:处理数组中的每个元素,并过滤元素,该函数中包含两个参数,第一个是当前数组元素的值,一个是当前数组元素的下标,即元素索引值。此函数应返回一个布尔值。另外,此函数可设置为一个字符串,当设置为字符串时,将视为“lambda-form”(缩写形式?),其中 a 代表数组元素,i 代表元素索引值。如“a > 0”代表“function(a){ return a > 0; }”

invert:布尔型可选项,默认值false,值为true或false, 如果 “invert” 为 false 或为设置,则函数返回数组中由过滤函数返回 true 的元素,当”invert” 为 true,则返回过滤函数中返回 false 的元素集。

解释完grep()的用法,现在来举个小例子:

复制代码 代码如下:
var arr=$.grep([0,1,2,3,4,5,6],function(n,i){
 return n>2
});

上面的例子返回[3,4,5,6],但是我们给invert的值为true,例如
复制代码 代码如下:
var arr=$.grep([0,1,2,3,4,5,6],function(n,i){
 return n>2
},ture);

所以现在返回的是[0,1,2],也就是被callback函数过滤掉的元素。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!