eachThe method is meant to being an immutable iterator, where as the map method can be used as a iterator, but is really Meant to manipulate the supplied array and return a new array.
Another important thing to note are that the each function returns the original array while the map function returns a NE W Array. If you overuse the return value of the map function you can potentially waste a lot of memory. For example: var items = [1,2,3,4];$.each (items, function () { alert (' This was ' + this);}); var newitems = $.map (items, function (i) { return i + 1;}); /NewItems is [2,3,4,5]you can also use the map function to remove a item from an array. for example:var items = [0,1,2,3,4,5,6,7,8,9];var itemslessthanequalfive = $.map (items, function (i)} { //Removes all I TEMs > 5 if (i > 5) return null; return i;}); /itemslessthanequalfive = [0,1,2,3,4,5]
You'll also note that's not this mapped in the map function. You'll have to supply the first parameter in the callback (eg we used i above). Ironically, the callback arguments used in the all method is the reverse of the callback arguments in the map function s o Be careful. Map (arr, function (Elem, index) {});//Versus each (arr, function (index, elem) {});
|