The following small series will bring you a forEach, $. each, and map method recommendation in JS. I think it is quite good. Now I will share it with you and give you a reference. Let's take a look at it. forEach is the most basic new Array method in ecma5. it is traversal and loop. For example:
[1, 2, 3, 4]. forEach (alert );
Equivalent to the for loop below
var array = [1, 2, 3, 4];for (var k = 0, length = array.length; k < length; k++) { alert(array[k]);}
Array in the newly added method of ES5, all parameters are of the function type. By default, parameters are passed. function callback in the forEach method supports three parameters, and 1st parameters are the retrieved Array content; the first is the corresponding array index, and the second is the array itself.
Therefore, we have:
[].forEach(function(value, index, array) { // ...});
Compare the $. each method in jQuery:
$.each([], function(index, value, array) { // ...});
We will find that the 1st and 2nd parameters are the opposite. Please remember. This is also true for a method similar to the following, for example, $. map.
var data=[1,3,4] ; var sum=0 ;data.forEach(function(val,index,arr){ console.log(arr[index]==val); // ==> true sum+=val })console.log(sum); // ==> 8
Map
The map here is not a map, but a ing ". []. Map (); basic usage is similar to the forEach method:
array.map(callback,[ thisObject]);
The callback parameters are also similar:
[].map(function(value, index, array) { // ...});
The role of the map method is not hard to understand. "ing" means that the original array is "mapped" to the corresponding new array. The following example calculates the square of a numerical item:
var data=[1,3,4]var Squares=data.map(function(val,index,arr){ console.log(arr[index]==val); // ==> true return val*val })console.log(Squares); // ==> [1, 9, 16]
Note: Since forEach and map are both ways to add arrays to ECMA5, browsers below ie9 are not supported yet (Internet Explorer). However, all the above functions can be extended from the Array prototype, such as the forEach method:
If (typeof Array. prototype. forEach! = "Function") {Array. prototype. forEach = function () {/* implement */};}
The forEach, $. each, and map methods in the preceding JS section are all the content shared by Alibaba Cloud xiaobian. I hope you can give us a reference and support for me.