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

Source: Internet
Author: User

The use of each function and the map function in jquery looks similar, but there is a bit of a difference.

One important difference is that each returns an array of the original and does not create a new one. The map method returns a new array. If you use map without the need, it can be a waste 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]

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

For example:

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) return null; return i;} ); Itemslessthanequalfive = [0,1,2,3,4,5]

This is also true when an array is required for deletion, so it is quite serious to use each or map as a result of the deletion.


This article is from the "Liu Bofang blog" blog, make sure to keep this source http://liubofang.blog.51cto.com/11162557/1792460

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

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.