Differences between map functions and each functions in jquery

Source: Internet
Author: User

The usage of the each function in jquery is similar to that of the map function, but there is still a difference.

An important difference is that each returns the original array and does not create a new array. The map method returns a new array. If map is used without any need, memory may be wasted.

For example:

Var items = [1, 2, 4]; $. each (items, function () {alert ('this is '+ this) ;}); var newItems =$. map (items, function (I) {return I + 1 ;}); // newItems is [2, 3, 4, 5]

When each is used, the original items array is changed. When map is used, items is not changed, but a new array is created.

For example:

Var items = [,]; var itemslessthan1_five = $. map (items, function (I) {// removes all items> 5 if (I> 5) return null; return I ;}); // itemslessthan1_five =, 4, 5]

This is also true when the array needs to be deleted. Therefore, the error of using each or map during deletion is still very 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.