The following editor will bring you a recommendation for forEach, $.each, and map methods in JS. The editor thinks it’s pretty good, so I’d like to share it with you now and give it as a reference. Let’s follow the editor to take a look.
forEach is the most basic one of the new Array methods in ECMA5, which is traversal and looping. For example, the following example:
[1, 2,3, 4].forEach(alert);
is equivalent to the following for loop
var array = [1, 2, 3, 4];
for (var k = 0, length = array.length; k < length; k++) {
alert(array[k]);
}
Array In the new methods of ES5, the parameters are all function types, and parameters are passed by default. The function callback in the forEach method supports 3 parameters. The first The first is the traversed array content; the second is the corresponding array index, and the third is the array itself.
So, we have:
[].forEach(function(value, index, array) {
// ...
}) ;
Compare the $.each method in jQuery:
##console.log(sum); // ==> 8
##mapThe map here is not a "map" ” means “mapping”. [].map(); The basic usage is similar to the forEach method: array.map(callback,[ thisObject]);
The parameters of callback are also similar:
[].map(function(value, index, array) {
// ...
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 ECMA5's new array methods, browsers below IE9 do not support it yet (that damn IE). However, all the above functions can be achieved by extending the Array prototype, such as the forEach method:
if (typeof Array.prototype.forEach != "function") {
Array.prototype.forEach = function() {
/* accomplish*/
The above is the detailed content of Introduction to forEach, $.each, and map methods in JS. For more information, please follow other related articles on the PHP Chinese website!