The difference between map function and each function in jquery _ function

Source: Internet
Author: User

The use of each function in jquery looks almost the same as the map function, but there is a difference.

One important difference is that each returns the original array, and no new array is created. The map method returns a new array. If you use a map if it is not necessary, you can create a waste of memory.

e.g.

  var items = [1,2,3,4];  $.each (items, function () {
      alert (' it ' + this);
  });
  var newitems = $.map (items, function (i) {return
      i + 1;
  });
  NewItems is [2,3,4,5]

When you use each, you change the original items array, and when you use map, do not change items, just create a new array.

e.g.

    var items = [0,1,2,3,4,5,6,7,8,9];    var itemslessthanequalfive = $.map (items, function (i) {
      //Removes all items > 5
      if (i > 5) 
        ret Urn null;
      return i;
    });
      Itemslessthanequalfive = [0,1,2,3,4,5]

This is also true when an array is required for deletion, so the error of using each or map for deletion is quite serious.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.