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

前端 未结 2 984
Happy的楠姐
Happy的楠姐 2021-02-13 11:36

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

I want a simple answer as far as possible.

相关标签:
2条回答
  • 2021-02-13 11:49

    $.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.

    0 讨论(0)
  • 2021-02-13 11:53

    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

    0 讨论(0)
提交回复
热议问题