1、原生JS forEach()和map()遍历javascript
共同点:html
1.都是循环遍历数组中的每一项。java
2.forEach() 和 map() 里面每一次执行匿名函数都支持3个参数:数组中的当前项item,当前项的索引index,原始数组input。jquery
3.匿名函数中的this都是指Window。数组
4.只能遍历数组。函数
1.forEach()this
没有返回值。spa
arr[].forEach(function(value,index,array){.net
//do somethingprototype
})
- 参数:value数组中的当前项, index当前项的索引, array原始数组;
- 数组中有几项,那么传递进去的匿名回调函数就须要执行几回;
- 理论上这个方法是没有返回值的,仅仅是遍历数组中的每一项,不对原来数组进行修改;可是能够本身经过数组的索引来修改原来的数组;
- var ary = [12,23,24,42,1];
- var res = ary.forEach(function (item,index,input) {
- input[index] = item*10;
- })
- console.log(res);
- console.log(ary);
2.map()
有返回值,能够return 出来。
arr[].map(function(value,index,array){
//do something
return XXX
})
- 参数:value数组中的当前项,index当前项的索引,array原始数组;
- 区别:map的回调函数中支持return返回值;return的是啥,至关于把数组中的这一项变为啥(并不影响原来的数组,只是至关于把原数组克隆一份,把克隆的这一份的数组中的对应项改变了);
- var ary = [12,23,24,42,1];
- var res = ary.map(function (item,index,input) {
- return item*10;
- })
- console.log(res);
- console.log(ary);
兼容写法:
无论是forEach仍是map在IE6-8下都不兼容(不兼容的状况下在Array.prototype上没有这两个方法),那么须要咱们本身封装一个都兼容的方法,代码以下:
- Array.prototype.myForEach = function myForEach(callback,context){
- context = context || window;
- if('forEach' in Array.prototye) {
- this.forEach(callback,context);
- return;
- }
-
- for(var i = 0,len = this.length; i < len;i++) {
- callback && callback.call(context,this[i],i,this);
- }
- }
- Array.prototype.myMap = function myMap(callback,context){
- context = context || window;
- if('map' in Array.prototye) {
- return this.map(callback,context);
- }
-
- var newAry = [];
- for(var i = 0,len = this.length; i < len;i++) {
- if(typeof callback === 'function') {
- var val = callback.call(context,this[i],i,this);
- newAry[newAry.length] = val;
- }
- }
- return newAry;
- }
2、jQuery $.each()和$.map()遍历
共同点:
便可遍历数组,又可遍历对象。
1.$.each()
没有返回值。$.each()里面的匿名函数支持2个参数:当前项的索引i,数组中的当前项v。若是遍历的是对象,k 是键,v 是值。
$.each(arr, function(index,value){
//do something
})
- 参数:arr要遍历的数组,index当前项的索引,value数组中的当前项
- 第1个和第2个参数正好和以上两个函数是相反的,注意不要记错了
- $.each( ["a","b","c"], function(i, v){
- alert( i + ": " + v );
- });
- $("span").each(function(i, v){
- alert( i + ": " + v );
- });
- $.each( { name: "John", lang: "JS" }, function(k, v){
- alert( "Name: " + k + ", Value: " + v );
- });
2.$.map()
有返回值,能够return 出来。$.map()里面的匿名函数支持2个参数和$.each()里的参数位置相反:数组中的当前项v,当前项的索引 i。若是遍历的是对象,k 是键,v 是值。若是是$("span").map()形式,参数顺序和$.each() $("span").each()同样。
$.map(arr, function(value, index){
//do something
return XXX
})
- var arr=$.map( [0,1,2], function(v){
- return v + 4;
- });
- console.log(arr);
- $.map({"name":"Jim","age":17},function(k, v){
- console.log( k+":"+v );
- });
连接:
http://www.cnblogs.com/lpy001/p/6196820.html
http://blog.csdn.net/huangpb123/article/details/52756303