您的位置:首页 > Web前端 > JQuery

原生JS forEach()和map()遍历的区别以及兼容写法,jQuery $.each()和$.map()遍历

2017-09-11 19:30 1056 查看

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

共同点:

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

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

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

4.只能遍历数组。


1.forEach()

没有返回值。

arr[].forEach(function(value,index,array){

  //do something

})


参数: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);//--> undefined;
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);//-->[120,230,240,420,10];  原数组拷贝了一份,并进行了修改
console.log(ary);//-->[12,23,24,42,1];  原数组并未发生变化


兼容写法:

不管是forEach还是map在IE6-8下都不兼容(不兼容的情况下在Array.prototype上没有这两个方法),那么需要我们自己封装一个都兼容的方法,代码如下:

/**
* forEach遍历数组
* @param callback [function] 回调函数;
* @param context [object] 上下文;
*/
Array.prototype.myForEach = function myForEach(callback,context){
context = context || window;
if('forEach' in Array.prototye) {
this.forEach(callback,context);
return;
}
//IE6-8下自己编写回调函数执行的逻辑
for(var i = 0,len = this.length; i < len;i++) {
callback && callback.call(context,this[i],i,this);
}
}


/**
* map遍历数组
* @param callback [function] 回调函数;
* @param context [object] 上下文;
*/
Array.prototype.myMap = function myMap(callback,context){
context = context || window;
if('map' in Array.prototye) {
return this.map(callback,context);
}
//IE6-8下自己编写回调函数执行的逻辑
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;
}


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

共同点:

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

1.$.each()

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

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


$("span").each(function(i, n){
alert( i + ": " + n );
});


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


2.$.map()

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

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


$.map({"name":"Jim","age":17},function(i,n){
console.log(i+":"+n);
});


原文链接:原生JS forEach()和map()遍历的区别以及兼容写法
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  jquery 遍历 数组 js 方法