What is the difference between $.map and $.grep in jQuery
What i开发者_JAVA技巧s the difference between $.map
and $.grep
in jQuery?
I want a simple answer as far as possible.
I will assume you mean $.grep
and $.map
. The difference is that we use $.grep
to filter an array while we use $.map
to apply a function to each item in the array.
Here is a much better explanation than I can make:
http://onwebdev.blogspot.com/2011/03/jquery-grep-and-map-example-and-syntax.html
$.map
method can be used as an iterator, but is meant to manipulate the array and return a new array.
var items = ['A','B','C','A'];
var items = $.map(items, function(item) {
if (item == 'A')
return null;
return item;
});
items is now new array. ['B','C']
or
var items = $.map(items, function(item) {
if (item == 'A')
return 'A'+'B';
return item;
});
output will be ['AB', 'B', 'C', 'AB']
$.grep
is used for filtering
var items = $.grep(items, function(item) {
return item != 'A';
});
items is now ['B','C']
however
var items = $.grep(items, function(item) {
if (item == 'A')
return 'A'+'B';
return item;
})
will return ['A', 'B', 'C', 'A']
as it is not producing new stuff - it reduces the existing.
精彩评论