美文网首页
forEach和map方法的对比

forEach和map方法的对比

作者: DontPushMeForev | 来源:发表于2016-12-15 11:10 被阅读0次

1.forEach —— 遍历

forEach遍历数组,对原来的数据操作,改变原数组

参数介绍:forEach方法中第一个参数是回调函数,它支持3个参数:

1. 第1个是遍历的数组内容

2. 第2个是对应索引

3. 第3个是数组自身

实例说明:

var arr=['zhangsan','lisi','wangwu','hello','world'];

       arr.forEach(function (value,index) {

       console.log(value);

       console.log(index);

})

输出结果如下图:

2. Map()方法:

映射,创建新数组

实例:

var users = [

       {name: "张含韵", "email": "zhang@email.com"},

       {name: "江一燕",  "email": "jiang@email.com"},

       {name: "李小璐",  "email": "li@email.com"}

];

var emails=users.map(function (user) {

       return user.email;

})

console.log(emails);

输出结果如下:

相关文章

网友评论

      本文标题:forEach和map方法的对比

      本文链接:https://www.haomeiwen.com/subject/vbnwmttx.html