The difference between map function and each function in jquery is introduced by example

  • 2020-03-30 03:27:11
  • OfStack

The & # 8203; The use of the each and map functions in jquery looks similar, but there is a slight difference.

The & # 8203; One important difference is that each returns the original array and does not create a new array. The map method returns a new array. If you use a map when you don't need it, you can waste memory.

The & # 8203; Such as:


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]


The & # 8203; Using each, you change the same items array, while using map, you don't change items, you just create a new array.

The & # 8203; Such as:


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 needs to be deleted, so using an each or map incorrectly while deleting can be pretty serious.


Related articles: