forEach,map遍历数组的区别

1、原生JS forEach()和map()遍历javascript

共同点:java

    1.都是循环遍历数组中的每一项。数组

    2.forEach() 和 map() 里面每一次执行匿名函数都支持3个参数:数组中的当前项item,当前项的索引index,原始数组input。函数

    3.匿名函数中的this都是指Window。this

    4.只能遍历数组。spa

1.forEach().net

   没有返回值。prototype

arr[].forEach(function(value,index,array){blog

  //do something索引

})

  • 参数:value数组中的当前项, index当前项的索引, array原始数组;
  • 数组中有几项,那么传递进去的匿名回调函数就须要执行几回;
  • 理论上这个方法是没有返回值的,仅仅是遍历数组中的每一项,不对原来数组进行修改;可是能够本身经过数组的索引来修改原来的数组;
[javascript]  view plain  copy
 
  1. var ary = [12,23,24,42,1];  
  2. var res = ary.forEach(function (item,index,input) {  
  3.        input[index] = item*10;  
  4. })  
  5. console.log(res);//--> undefined;  
  6. console.log(ary);//--> 经过数组索引改变了原数组;  


2.map() 

有返回值,能够return 出来。

arr[].map(function(value,index,array){

  //do something

  return XXX

})

  • 参数:value数组中的当前项,index当前项的索引,array原始数组;
  • 区别:map的回调函数中支持return返回值;return的是啥,至关于把数组中的这一项变为啥(并不影响原来的数组,只是至关于把原数组克隆一份,把克隆的这一份的数组中的对应项改变了);
[javascript]  view plain  copy
 
  1. var ary = [12,23,24,42,1];  
  2. var res = ary.map(function (item,index,input) {  
  3.     return item*10;  
  4. })  
  5. console.log(res);//-->[120,230,240,420,10];  原数组拷贝了一份,并进行了修改
  6. console.log(ary);//-->[12,23,24,42,1];  原数组并未发生变化

兼容写法:

 

无论是forEach仍是map在IE6-8下都不兼容(不兼容的状况下在Array.prototype上没有这两个方法),那么须要咱们本身封装一个都兼容的方法,代码以下:

[javascript]  view plain  copy
 
  1. /** 
  2. * forEach遍历数组 
  3. * @param callback [function] 回调函数; 
  4. * @param context [object] 上下文; 
  5. */  
  6. Array.prototype.myForEach = function myForEach(callback,context){  
  7.     context = context || window;  
  8.     if('forEach' in Array.prototye) {  
  9.         this.forEach(callback,context);  
  10.         return;  
  11.     }  
  12.     //IE6-8下本身编写回调函数执行的逻辑  
  13.     for(var i = 0,len = this.length; i < len;i++) {  
  14.         callback && callback.call(context,this[i],i,this);  
  15.     }  
  16. }  

 

[javascript]  view plain  copy
 
    1. /** 
    2. * map遍历数组 
    3. * @param callback [function] 回调函数; 
    4. * @param context [object] 上下文; 
    5. */  
    6. Array.prototype.myMap = function myMap(callback,context){  
    7.     context = context || window;  
    8.     if('map' in Array.prototye) {  
    9.         return this.map(callback,context);  
    10.     }  
    11.     //IE6-8下本身编写回调函数执行的逻辑  
    12.     var newAry = [];  
    13.     for(var i = 0,len = this.length; i < len;i++) {  
    14.         if(typeof  callback === 'function') {  
    15.             var val = callback.call(context,this[i],i,this);  
    16.             newAry[newAry.length] = val;  
    17.         }  
    18.     }  
    19.     return newAry;  
相关文章
相关标签/搜索