jQuery.grep() 方法
實例
過濾原始數組
< div ></ div > < p ></ p > < span ></ span > < script > $ ( function ( ) {
var arr = [ 1 , 9 , 3 , 8 , 6 , 1 , 5 , 9 , 4 , 7 , 3 , 8 , 6 , 9 , 1 ] ; $ ( " div " ) . text ( arr . join ( " , " ) ) ; arr = jQuery . grep ( arr , function ( n , i ) {
return ( n !== 5 && i > 4 ) ; } ) ; $ ( " p " ) . text ( arr . join ( " , " ) ) ; arr = jQuery . grep ( arr , function ( a ) {
return a !== 9 ; } ) ; $ ( " span " ) . text ( arr . join ( " , " ) ) ; } ) </ script >
嘗試一下»
定義和用法
$.grep() 函數使用指定的函數過濾數組中的元素,並返回過濾後的數組。
提示:源數組不會受到影響,過濾結果只反映在返回的結果數組中。
語法
$.grep( array, function [, invert ] )
参数 | 描述 |
---|---|
array | Array类型 将被过滤的数组。 |
function | Function类型 指定的过滤函数。grep()方法为function提供了两个参数:其一为当前迭代的数组元素,其二是当前迭代元素在数组中的索引。 |
invert | 可选。 Boolean类型 默认值为false,指定是否反转过滤结果。如果参数invert为true,则结果数组将包含function返回false的所有元素。 |
更多實例
過濾原始數組
過濾出數組中值大於0 的元素。
過濾原始數組
過濾出數組中值不大於0 的元素。