An explanation of the use of Foeach and maps in arrays
Same point:
1. Each item in the loop iterates through an array (just an array).
Each execution of the anonymous function in 2.forEach () and map () supports 3 parameters: the current item in the array value, the index of the current item, and the original array array.
3. This in the anonymous function refers to window.
4.ie6-8 is incompatible, by extending this method on the array prototype can be implemented
Form:
[].ForEach(function(Value,Inede,Array{ //...});[].Map(function(Value,Inede,Array{ //...});Array.prototype.Myforeach = function Myforeach(Callback,Context{Context=Context||Window; if(' ForEach ' inch Array.Prototye){ This.ForEach(Callback,Context; return; } //ie6-8 Write your own callback function execution Logic for(varI= 0,Len= This.length;I<Len;I++){Callback&& Callback.Pager(Context, ThisI,I, This); } }
ForEach ():
Parameter: The current item in the value array, index of the current item, array original array;
There are several items in the array, then the anonymous callback function passed in will need to be executed several times.
No return value, simply traversing each item in the array, not modifying the original array, but you can modify the original array by its index;
var= [1,23,45,56,7,8]; data.forEach(function(value,index,{ = arr[index]*10; });
Map ():
There is a return value, you can return it.
Parameter: The current item in the value array, index of the current item, array original array;
Difference: The callback function in map supports return value, which is equivalent to changing each item in the array (it does not affect the original array, but it is equivalent to cloning a copy of the original array and changing the corresponding item in the array of the cloned copy);
varData=[Ten, the, the,560, -, the]; varData1= Data.Map(function(Value,Index,Arr{ returnvalue/Ten; }); Console.Log(data); Console.Log(DATA1);//(6) [560 , +,]//(6) [1, 23°c, 7, 8]
$.each and $.map in jquery
You can iterate over the object compared to the native JS feature extension.
Form:
$.each(obj,function(index,{ //...});$.map(obj,function(index,{ //...});
$.each ()
no return value. The anonymous function inside the $.each () supports 2 parameters: The current item's index I, the current item in the array, v. If the object is traversed, K is the key and V is the value.
$.each{name:"assassin",age:23},function(k, v){ console.log"Key: "++", Value: "+ v ); });/*Key: name, Value: assassinKey: age, Value: 23*/
$.map ()
There is a return value, you can return it. The anonymous function inside $.map () supports 2 parameters and $.each () in the opposite position: the current item in the array V, the index of the current item. If the object is traversed, K is the key and V is the value.
$.map{name:"assassin",age:23},function(k, v){ console.log"Key: "++", Value: "+ v ); }); //Key: assassin, Value: name//Key: 23, Value: age
The usage of Foeach and map in the
JS array is detailed in $.each and $.map in JQ