JQuery map vs. each author the solution, right?

Source: Internet
Author: User

in JQuery, the and functions seem to do the map each same thing. Is there any practical differences between the? When would your choose to use one instead of the other?

eachThe method is meant to being an immutable iterator, where as the map method can be used as a iterator, but is really Meant to manipulate the supplied array and return a new array.

Another important thing to note are that the each function returns the original array while the map function returns a NE W Array. If you overuse the return value of the map function you can potentially waste a lot of memory.

For example:

var items = [1,2,3,4];$.each (items, function () {  alert (' This was ' + this);}); var newitems = $.map (items, function (i) {  return i + 1;}); /NewItems is [2,3,4,5]you can also use the map function to remove a item from an array. for example:var items = [0,1,2,3,4,5,6,7,8,9];var itemslessthanequalfive = $.map (items, function (i)} {  //Removes all I TEMs > 5  if (i > 5)     return null;  return i;}); /itemslessthanequalfive = [0,1,2,3,4,5]

  

You'll also note that's not this mapped in the map function. You'll have to supply the first parameter in the callback (eg we used i above). Ironically, the callback arguments used in the all method is the reverse of the callback arguments in the map function s o Be careful.

Map (arr, function (Elem, index) {});//Versus each (arr, function (index, elem) {});

  

JQuery map vs. each author the solution, right?

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.