Home > Web Front-end > JS Tutorial > body text

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

黄舟
Release: 2017-07-19 16:27:20
Original
1301 people have browsed it

The usage of each function and map function in jquery seems to be similar, but in fact there is still a little difference.

One important difference is that each returns the original array and does not create a new array. The map method will return a new array. If map is used unnecessarily, memory may be wasted.

For example:

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

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

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]
Copy after login

The same is true when an array needs to be deleted, so the consequences of incorrectly using each or map when deleting are quite serious.

The above is the detailed content of Share the difference between the map function and each function in jquery. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!