JS forEach()和map()遍历,jQuery$.each()和$.map()遍历

一、原生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
原文地址:https://www.cnblogs.com/caiyuqin/p/7483545.html