jQuery.grep()
jQuery.grep( array, function(elementOfArray, indexInArray), [ invert ] ) 返回: Array
描述: 查找滿足過(guò)濾功能數(shù)組元素。原始數(shù)組不受影響。
-
version added: 1.0jQuery.grep( array, function(elementOfArray, indexInArray), [ invert ] )
array該數(shù)組用來(lái)搜索。
function(elementOfArray, indexInArray)該函數(shù)來(lái)處理每個(gè)項(xiàng)目的比對(duì)。第一個(gè)參數(shù)給函數(shù)是項(xiàng)目,第二個(gè)參數(shù)是索引。該函數(shù)應(yīng)返回一個(gè)布爾值。
this將是全局的窗口對(duì)象。invert如果“invert”為false,或沒(méi)有提供,函數(shù)返回一個(gè)所有元素組成的數(shù)組對(duì)于“callback”返回true。如果“invert”為true,函數(shù)返回一個(gè)所有元素組成的數(shù)組對(duì)于“callback”返回false。
$.grep()方法刪除數(shù)組必要項(xiàng)目,以使所有剩余項(xiàng)目通過(guò)提供的測(cè)試。該測(cè)試是一個(gè)函數(shù)傳遞一個(gè)數(shù)組項(xiàng)和該數(shù)組內(nèi)的項(xiàng)目的索引。只有當(dāng)測(cè)試返回true,該數(shù)組項(xiàng)將返回到結(jié)果數(shù)組中。
該過(guò)濾器的函數(shù)將被傳遞兩個(gè)參數(shù):當(dāng)前數(shù)組項(xiàng)和它的索引。該過(guò)濾器函數(shù)必須返回'true'以包含在結(jié)果數(shù)組項(xiàng)。
Examples:
Example: Filters the original array of numbers leaving that are not 5 and have an index greater than 4. Then it removes all 9s.
<!DOCTYPE html>
<html>
<head>
<style>
div { color:blue; }
p { color:green; margin:0; }
span { color:red; }
</style>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
<div></div>
<p></p>
<span></span>
<script>
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>
</body>
</html>
Demo:
Example: Filter an array of numbers to include only numbers bigger then zero.
$.grep( [0,1,2], function(n,i){
return n > 0;
});
Result:
[1, 2]
Example: Filter an array of numbers to include numbers that are not bigger than zero.
$.grep( [0,1,2], function(n,i){
return n > 0;
},true);
Result:
[0]