jQuery.grep()
jQuery.grep( array, function(elementOfArray, indexInArray), [ invert ] ) 返回: Array
描述: 查找滿足過濾功能數(shù)組元素。原始數(shù)組不受影響。
-
version added: 1.0jQuery.grep( array, function(elementOfArray, indexInArray), [ invert ] )
array該數(shù)組用來搜索。
function(elementOfArray, indexInArray)該函數(shù)來處理每個項目的比對。第一個參數(shù)給函數(shù)是項目,第二個參數(shù)是索引。該函數(shù)應(yīng)返回一個布爾值。
this將是全局的窗口對象。invert如果“invert”為false,或沒有提供,函數(shù)返回一個所有元素組成的數(shù)組對于“callback”返回true。如果“invert”為true,函數(shù)返回一個所有元素組成的數(shù)組對于“callback”返回false。
$.grep()方法刪除數(shù)組必要項目,以使所有剩余項目通過提供的測試。該測試是一個函數(shù)傳遞一個數(shù)組項和該數(shù)組內(nèi)的項目的索引。只有當(dāng)測試返回true,該數(shù)組項將返回到結(jié)果數(shù)組中。
該過濾器的函數(shù)將被傳遞兩個參數(shù):當(dāng)前數(shù)組項和它的索引。該過濾器函數(shù)必須返回'true'以包含在結(jié)果數(shù)組項。
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]