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]
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]
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!