First, native JS ForEach () and map () traversal
Common:
1. All loops iterate through each item in the array.
Each execution of the anonymous function in 2.forEach () and map () supports 3 parameters: the current item in the array item, the index of the current item, and the original array input.
3. This in the anonymous function refers to window.
4. Only the array can be traversed.
1.forEach ()
There is no return value, and the original array is modified.
var ary = [12,23,24,42,1]; var res = ary.forEach(function (item,index,input) { input[index] = item*10; }) console.log(res);//-->undefined; console.log(ary);//-->[ 120, 230, 240, 420, 10 ];
2.map ()
There is a return value, you can return it. The original array is not modified.
var ary = [12,23,24,42,1]; var res = ary.map(function (item,index,input) { return item*10; }) console.log(res);//-->[120,230,240,420,10];
Second, JQuery. eacH() and . Map () Traversal
Common:
You can iterate through the array and iterate over the object.
1.$.each ()
no return value. The anonymous function in $.each () supports 2 parameters: Index I of the current item, current item n in the array. If the object is traversed, K is the key and n is the value.
$.each( ["a","b","c"], function(i, n){ console.log( i + ": " + n ); }); // 0: a // 1: b // 2: c
"John", lang: "JS" }, function(k, n){ console.log( "Name: " + k + ", Value: " + n ); }); //Name: name, Value: John // Name: lang, Value: JS
2.$.map ()
There is a return value, you can return it..MAP()InSurfaceOfPunicNameLetter number Hold 2 parameter number The arguments in. each () are in the opposite position: the current item n in the array, and the index of the current item. If the object is traversed, I is the value and n is the key. If it is("SPAN").MAP()Shape , parameter sequence and . each (), $ ("span").
var arr=$.map( [0,1,2], function(n,i){ return n+i; }); console.log(arr); //[ 0, 2, 4 ]$.map({"name":"Jim","age":17},function(n,i){ console.log(n+":"+i); }); //Jim:name //17:age
Native JS ForEach () and map () traversal, Jquery$.each (), and $.map () traversal