JS中的forEach、$.each、map方法

forEach是ECMA5中Array新方法中最基本的一个,就是遍历,循环。例如下面这个例子:

[1, 2 ,3, 4].forEach(alert);

等同于下面这个for循环

1 var array = [1, 2, 3, 4];
2 for (var k = 0, length = array.length; k < length; k++) {
3  alert(array[k]);
4 }

Array在ES5新增的方法中,参数都是function类型,默认有传参,forEach方法中的function回调支持3个参数,第1个是遍历的数组内容;第2个是对应的数组索引,第3个是数组本身。

因此,我们有:

[].forEach(function(value, index, array) {
  // ...
});
 

对比jQuery中的$.each方法:

$.each([], function(index, value, array) {
  // ...
});
 

会发现,第1个和第2个参数正好是相反的,大家要注意了,不要记错了。后面类似的方法,例如$.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

这里的map不是“地图”的意思,而是指“映射”。[].map(); 基本用法跟forEach方法类似:

array.map(callback,[ thisObject]);

callback的参数也类似:

[].map(function(value, index, array) {
  // ...
});
 

map方法的作用不难理解,“映射”嘛,也就是原数组被“映射”成对应新数组。下面这个例子是数值项求平方:

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]
 

注意:由于forEach、map都是ECMA5新增数组的方法,所以ie9以下的浏览器还不支持(万恶的IE啊),不过呢,可以从Array原型扩展可以实现以上全部功能,例如forEach方法:

if (typeof Array.prototype.forEach != "function") {
  Array.prototype.forEach = function() {
    /* 实现 */
  };
}

引用至:http://www.jb51.net/article/81955.htm

原文地址:https://www.cnblogs.com/AaronNotes/p/6529970.html