码迷,mamicode.com
首页 > Web开发 > 详细

js中的forEach和map的区别

时间:2018-04-02 14:24:04      阅读:186      评论:0      收藏:0      [点我收藏+]

标签:利用   表示   兼容   有一个   his   item   报错   返回值   reac   

我们先来看两者之间的相同之处

var arr = [‘a‘,‘b‘,‘c‘,‘d‘];

arr.forEach(function(item,index,arr){    //item表示数组中的每一项,index标识当前项的下标,arr表示当前数组
    console.log(item);
    console.log(index);
    console.log(arr);
    console.log(this);
},123);      //这里的123参数,表示函数中的this指向,可写可不写,如果不写,则this指向window


arr.map(function(item,index,arr){   //参数含义同forEach
    console.log(item);
    console.log(index);
    console.log(arr);
    console.log(this);
},123);

运行之后,可以看出两者参数没有任何的区别,除此之外两者之间还有一个特性,就是不能停止里面的遍历,除非程序报错,那么两者之间的区别在那里呢???

在于返回值!!!

var a = arr.forEach(function(item,index,arr){ 
    return 123
});

var b = arr.map(function(item,index,arr){
    return 123
}); 

console.log(a);    //undefined
console.log(b);    //[123,123,123,123]

我们可以利用map的这个特性做哪些事情呢,比如

var b = arr.map(function(item,index,arr){
    return item+‘a‘;
}); 

console.log(b); //["aa", "ba", "ca", "da"]

forEach是es3中推出的方法,map是es5中推出的方法,目前在ie的低版本中都还有一些兼容性问题。

js中的forEach和map的区别

标签:利用   表示   兼容   有一个   his   item   报错   返回值   reac   

原文地址:https://www.cnblogs.com/chenzhiyu/p/8692845.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!