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

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

共同点:

1.都是循环遍历数组中的每一项。
2.forEach() 和 map() 里面每一次执行匿名函数都支持3个参数:数组中的当前项item,当前项的索引index,原始数组input。
3.匿名函数中的this都是指Window。
4.只能遍历数组。

1.forEach()

没有返回值。

var ary = [12,23,24,42,1];  
    var res = ary.forEach(function (item,index,input) {  
           input[index] = item*10;  
    })  
    console.log(res);//-->undefined;  
    console.log(ary);//-->[ 120, 230, 240, 420, 10 ];

2.map()

有返回值,可以return 出来。

var ary = [12,23,24,42,1];  
var res = ary.map(function (item,index,input) {  
    return item*10;  
})  
console.log(res);//-->[120,230,240,420,10];  
console.log(ary);//-->[12,23,24,42,1]; 

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

共同点:

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

1.$.each()

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

$.each( ["a","b","c"], function(i, n){  
  console.log( i + ": " + n );  
}); 
  // 0: a
  // 1: b
  // 2: c
 $.each( { name: "John", lang: "JS" }, function(k, n){  
        console.log( "Name: " + k + ", Value: " + n );  
    });  
     //Name: name, Value: John 
    // Name: lang, Value: JS

2.$.map()

有返回值,可以return 出来。 .map()2 .each()里的参数位置相反:数组中的当前项n,当前项的索引i。如果遍历的是对象,i 是值,n 是键。如果是 ("span").map() .each() ,$(“span”).each()一样。

var arr=$.map( [0,1,2], function(n,i){  
         return n+i;
    });  
    console.log(arr); 
    //[ 0, 2, 4 ]

$.map({"name":"Jim","age":17},function(n,i){  
     console.log(n+":"+i);  
 }); 
    //Jim:name
    //17:age
发布了22 篇原创文章 · 获赞 22 · 访问量 10万+

猜你喜欢

转载自blog.csdn.net/liang526011569/article/details/69949829
今日推荐