js數組的forEach與map方法


數組對象的作用是:使用單獨的變量名來存儲一系列的值。
 
我們今天來說一下數組的forEach與map方法
  • forEach 用於調用數組的每個元素
  • map 返回一個與原數組長度相等的新數組 
1、forEach() 
 
forEach() 方法用於調用數組的每個元素,並將元素傳遞給回調函數。
注意: forEach() 對於空數組是不會執行回調函數的
參數:function(currentValue, index, arr)
  • currentValue   必需。當前元素
  • index      可選。當前元素的索引值。
  • arr       可選。當前元素所屬的數組對象。 
 
1)使用forEach遍歷數組
1 var arr=[1,2,3,4,5,6,7]; 2 arr.forEach(function(a,b,c){ 3  console.log(a,b,c); 4 })
打印結果:如下
 
 2)使用forEach可以跳過空元素
1 var arr = [1, 2, 3, 5, , 6, 7, 8, 9]; 2 arr.forEach(function(item, index) { 3  console.log(item, index); 4 })
打印結果,如下
3)使用forEach復制數組的方法 (全部復制,不跳過空元素,)
1 var arr = [2, 4, 6, , 8, 3, 2]; 2 var arr1 = []; 3 arr.forEach(function(item, index) { 4     arr1[index] = item; 5 }) 6 console.log(arr1);
打印結果:如下
 
2、map()
 
map() 方法返回一個新數組,數組中的元素為原始數組元素調用函數處理后的值。
map() 方法按照原始數組元素順序依次處理元素。
注意: map() 不會對空數組進行檢測。
注意: map() 不會改變原始數組。
 
參數:function(currentValue, index, arr)
  • currentValue   必需。當前元素
  • index         可選。當前元素的索引值。
  • arr             可選。當前元素所屬的數組對象。 

 

1)遍歷數組 ----- map會返回一個與原數組長度相等的新數組
1 var arr = [3, 5, 7, 9, , 1, 2, 4]; 2 var arr2 = arr.map(function(item, index, arr) { 3  console.log(item, index, arr); 4 });
打印結果:如下
2)在map中使用return 就是在對應的下標中添加對應的數據
例1:
1 var arr = [3, 5, 7, 9, , 1, 2, 4]; 2 var arr2 = arr.map(function(item, index, arr) { 3     // 在map中使用return 就是在對應的下標中添加對應的數據
4     return "a"; 5 }); 6 console.log(arr2);
打印結果:如下
例2:
1 var arr = [3, 5, 7, 9, , 1, 2, 4]; 2 var arr3 = arr.map(function(item, index, arr) { 3     // 在map中使用return 就是在對應的下標中添加對應的數據
4     return item + 10; 5 }); 6 console.log(arr3);

打印結果:如下

 

3、forEach() 和 map() 兩者區別 
 
 1) forEach()返回值是undefined,不可以鏈式調用。
1 var arr = [1, 2, 3, 4, 5, , 7, 8, 9]; 2 var arr1 = arr.forEach(function(item, index, arr) { 3     // 使用return無效
4     return arr1; //undefined
5 }); 6 console.log(arr1);
打印結果:如下
 
2) map()返回一個新數組,原數組不會改變。
1 var arr = [1, 3, 5, 7, 2, 4, 6, 8]; 2 var arr1 = arr.map(function(item) { 3     if (item > 4) { 4         return item; 5  } 6 }); 7 console.log(arr); 8 console.log(arr1);
打印結果:如下
 
 
 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM