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

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

[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个是数组自己。this

所以,咱们有:spa

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

对比jQuery中的$.each方法:.net

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

会发现,第1个和第2个参数正好是相反的,你们要注意了,不要记错了。后面相似的方法,例如$.map也是如此。prototype

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
 

mapcode

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

array.map(callback,[ thisObject]);

callback的参数也相似:blog

[].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