---
title: "JavaScript中的数组遍历forEach()与map()方法和jQuery 中的$.each()于$.map()"
author: "jiage17"
date: "2018-10-29T16:27:05Z"
tags: []
categories: ["Web前端"]
slug: "javascript-foreach-map-jquery-each-map"
draft: false
lastmod: "2018-10-29T16:34:32Z"
id: 2432909
url: "https://jiage17.iteye.com/blog/2432909"
---

- **forEach用法**
- 高级浏览器支持forEach方法  
  语法：forEach和map都支持2个参数：一个是回调函数（item,index,list）和上下文；

<!--THE END-->

- forEach:用来遍历数组中的每一项；这个方法执行是没有返回值的，对原来数组没有影响；
- 数组中有几项，那么传递进去的匿名回调函数就需要执行几次；
- 每一次执行匿名函数的时候，还给其传递了三个参数值：数组中的当前项item,当前项的索引index,原始数组input；
- 理论上这个方法是没有返回值的，仅仅是遍历数组中的每一项，不对原来数组进行修改；但是我们可以自己通过数组的索引来修改原来的数组；
- forEach方法中的this是ary,匿名回调函数中的this默认是window；
- 以下两种写法均可以，第二种写法比第一种多了this。

```
var ary = [12,23,24,42,1];
var res = ary.forEach(function (item,index,ary) {
    ary[index] = item*10;
})
console.log(res);//-->undefined;
console.log(ary);//-->会对原来的数组产生改变；
```

```
var ary = [12,23,24,42,1];
var res = ary.forEach(function (item,index,ary) {
    ary[index] = item*10;
},this)
console.log(res);//-->undefined;
console.log(ary);//-->会对原来的数组产生改变；
```

 

**map用法**

- map:和forEach非常相似，都是用来遍历数组中的每一项值的，用来遍历数组中的每一项；
- 区别：map的回调函数中支持return返回值；return的是什么，相当于把数组中的这一项变为什么；
- 并不影响原来的数组，只是相当于把原数组克隆一份，把克隆的这一份的数组中的对应项改变了；
- 不管是forEach还是map 都支持第二个参数值，第二个参数的意思是把匿名回调函数中的this进行修改。

 

[![复制代码](http://common.cnblogs.com/images/copycode.gif)]()

```
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()**

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

```
$.each( ["a","b","c"], function(i, n){  
  console.log( i + ": " + n );  
}); 
  // 0: a
  // 1: b
  // 2
```

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

 **JQuery中的$.map()**

有返回值，可以return 出来。

$.map()里面的匿名函数支持2个参数和$.each()里的参数位置相反：数组中的当前项n，当前项的索引i。如果遍历的是对象，i 是值，n 是键。如果是("span").map()形式，参数顺序和("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
```