一、原生JS forEach()和map()遍歷
共同點:
- 都是循環遍歷數組中的每一項。
- forEach() 和 map() 里面每一次執行匿名函數都支持3個參數:數組中的當前項item,當前項的索引index,原始數組array。
- 匿名函數中的this都是指Window。
- 只能遍歷數組。
forEach()方法:(沒有返回值)
arr[].forEach(function(value,index,array){ //do something })
- 參數:value數組中的當前項; index當前項的索;array原始數組;
- 數組中有幾項,那么傳遞進去的匿名回調函數就需要執行幾次;
- 理論上這個方法是沒有返回值的,僅僅是遍歷數組中的每一項,不對原來數組進行修改;但是可以自己通過數組的索引來修改原來的數組;
1 var arr = [12, 23, 24, 42, 1]; 2 var res = arr.forEach(function(value, index, arrNew) { 3 arrNew[index] = value * 10; 4 }) 5 console.log(res); //-->undefined; 6 console.log(arr); //-->[120,230,240,420,10]; 通過數組索引改變了原數組
map()方法:(沒有返回值,可以return出來)
arr[].map(function(value,index,array){ //do something })
- 參數:value數組中的當前項; index當前項的索引;array原始數組;
- 區別:map的回調函數中支持return返回值;return的是啥,相當於把數組中的這一項變為啥(並不影響原來的數組,只是相當於把原數組克隆一份,把克隆的這一份的數組中的對應項改變了);
1 var arr = [12, 23, 24, 42, 1]; 2 var res = arr.map(function(vlaue, index, arrNew) { 3 return vlaue * 10; 4 }) 5 console.log(res); //-->[120,230,240,420,10]; 原數組拷貝了一份,並進行了修改 6 console.log(arr); //-->[12,23,24,42,1]; 原數組並未發生變化
二、jQuery .each()和.map()遍歷
共同點:
即可遍歷數組,又可遍歷對象;
$.each()方法:(沒有返回值)
$.each(arr, function(index,element ){ //do something })
- 參數 index當前項的索引;element 數組中的當前項
- 注意:第1個和第2個參數正好和以上兩個函數是相反的;
遍歷數組:
1 var arr = [12, 23, 24, 42, 1]; 2 $.each(arr, function(index, value) { 3 console.log(index) // 0 1 2 3 4 4 console.log(element ) // 12 23 24 42 1 5 })
遍歷對象:
1 $.each({ name: "John", lang: "JS" }, function(k, n) { 2 console.log("Name: " + k + ", Value: " + n); 3 }); 4 //Name: name, Value: John 5 // Name: lang, Value: JS
$.map()方法:(沒有返回值,可以return出來)
- 參數: index當前項的索引;element 數組中的當前項
遍歷數組:
1 var arr = $.map([0, 1, 2], function(index, element) { 2 return index + element; 3 }); 4 console.log(arr);
遍歷對象:
1 $.map({ "name": "Jim", "age": 17 }, function(name, vlaue) { 2 console.log(name + ":" + vlaue); 3 }); 4 //Jim:name 5 //17:age