Home >Web Front-end >JS Tutorial >Example introduction to the difference between map function and each function in jquery_jquery

Example introduction to the difference between map function and each function in jquery_jquery

WBOY
WBOYOriginal
2016-05-16 16:43:261191browse

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

​One of the important differences 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.

Statement:
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