forEach与map

时间:2023-03-09 07:38:31
forEach与map

一、原生js forEach()和map()遍历

共同点:

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

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

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

4.只能遍历数组。

1.forEach()

没有返回值。

  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 出来。

  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上没有这两个方法),那么需要我们自己封装一个都兼容的方法,代码如下:

  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. }
  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;
  20. }

二、jQuery $.each()和$.map()遍历

共同点:

即可遍历数组,又可遍历对象。

1.$.each()

没有返回值。$.each()里面的匿名函数支持2个参数:当前项的索引i,数组中的当前项n。如果遍历的是对象,k 是键,n 是值。

  1. $.each( ["a","b","c"], function(i, n){
  2. alert( i + ": " + n );
  3. });
  1. $("span").each(function(i, n){
  2. alert( i + ": " + n );
  3. });

  1. $.each( { name: "John", lang: "JS" }, function(k, n){
  2. alert( "Name: " + k + ", Value: " + n );
  3. });

2.$.map()

有返回值,可以return 出来。$.map()里面的匿名函数支持2个参数和$.each()里的参数位置相反:数组中的当前项n,当前项的索引i。如果遍历的是对象,i 是值,n 是键。如果是$("span").map()形式,参数顺序和$.each()  $("span").each()一样。

  1. var arr=$.map( [0,1,2], function(n){
  2. return n + 4;
  3. });
  4. console.log(arr);
  1. $.map({"name":"Jim","age":17},function(i,n){
  2. console.log(i+":"+n);
  3. });

文章来自 http://blog.csdn.net/huangpb123/article/details/52756303