What is the difference between $.map
and $.grep
in jQuery?
jQuery中$ .map和$ .grep有什么区别?
I want a simple answer as far as possible.
我想尽可能简单的回答。
2 个解决方案
#1
21
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.
我假设你的意思是$ .grep和$ .map。不同之处在于我们使用$ .grep来过滤数组,而我们使用$ .map将函数应用于数组中的每个项目。
Here is a much better explanation than I can make:
这是一个比我能做的更好的解释:
http://onwebdev.blogspot.com/2011/03/jquery-grep-and-map-example-and-syntax.html
#2
10
$.map
method can be used as an iterator, but is meant to manipulate the array and return a new array.
$ .map方法可以用作迭代器,但是用于操作数组并返回一个新数组。
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']
items现在是新数组。 ['公元前']
or
var items = $.map(items, function(item) {
if (item == 'A')
return 'A'+'B';
return item;
});
output will be ['AB', 'B', 'C', 'AB']
输出将是['AB','B','C','AB']
$.grep
is used for filtering
$ .grep用于过滤
var items = $.grep(items, function(item) {
return item != 'A';
});
items is now ['B','C']
物品现在是['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.
将返回['A','B','C','A'],因为它不会产生新的东西 - 它会减少现有的东西。
#1
21
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.
我假设你的意思是$ .grep和$ .map。不同之处在于我们使用$ .grep来过滤数组,而我们使用$ .map将函数应用于数组中的每个项目。
Here is a much better explanation than I can make:
这是一个比我能做的更好的解释:
http://onwebdev.blogspot.com/2011/03/jquery-grep-and-map-example-and-syntax.html
#2
10
$.map
method can be used as an iterator, but is meant to manipulate the array and return a new array.
$ .map方法可以用作迭代器,但是用于操作数组并返回一个新数组。
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']
items现在是新数组。 ['公元前']
or
var items = $.map(items, function(item) {
if (item == 'A')
return 'A'+'B';
return item;
});
output will be ['AB', 'B', 'C', 'AB']
输出将是['AB','B','C','AB']
$.grep
is used for filtering
$ .grep用于过滤
var items = $.grep(items, function(item) {
return item != 'A';
});
items is now ['B','C']
物品现在是['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.
将返回['A','B','C','A'],因为它不会产生新的东西 - 它会减少现有的东西。