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
Release: 2016-05-16 16:43:26
Original
1183 people have browsed it

​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]
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.

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