javascript jQuery 中的 $.map 和 $.grep 有什么区别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6245140/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 20:02:06  来源:igfitidea点击:

What is the difference between $.map and $.grep in jQuery

javascriptjquery

提问by Tarek Saied

What is the difference between $.mapand $.grepin jQuery?

jQuery$.map$.grepjQuery 中有什么区别?

I want a simple answer as far as possible.

我想要一个尽可能简单的答案。

回答by IAmTimCorey

I will assume you mean $.grepand $.map. The difference is that we use $.grepto filter an array while we use $.mapto 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

http://onwebdev.blogspot.com/2011/03/jquery-grep-and-map-example-and-syntax.html

回答by Matas Vaitkevicius

$.mapmethod 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 现在是新数组。 ['B','C']

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']

$.grepis 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']因为它不会产生新的东西——它减少了现有的东西。