原生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

最后总结一下:

1.遍历数组

          1.1    原生js有两种方法都可以使用[for(var i;i<arr.length;i++){}-----for(var i in arr){}] 。

  1.2  jquery有两个函数共计四种方法都可以使用[$.each(arr,function(i,item){})----$(arr).each(function(i,item){})---$.map(arr,function(i,item){})-----$(arr).map(function(i,item){})]。

2.遍历对象 

        2.1    原生js有一种方法可以使用[for(var i in obj){}] 。

        2.2    jquery有两个函数共计两种方法可以使用[$.each(obj,function(i,item){})------$.map(obj,function(i,item){})]。

猜你喜欢

转载自blog.csdn.net/weixin_38055381/article/details/82177431