forEach和map方法的区别

forEach()和map()两个方法都是ECMA5中Array引进的新方法,主要作用是对数组的每个元素执行一次提供的函数,但是它们之间还是有区别的。jQuery也有一个方法$.each(),长得和forEach()有点像,功能也类似。但是从本质上还是有很大的区别的,那么我们探探究竟。

//forEach
array.forEach(callback(currentValue, index, array){
    //do something
}, this)
 
//或者
array.forEach(callback(currentValue, index, array){
    //do something
})  
 
//map:
var new_array = arr.map(callback[, thisArg]) 
 
//$.each()
$(selector).each(function(index,element))  //注意参数的顺序

callback: 为数组中每个元素执行的函数,该函数接收三个参数,

参数一:当前数组中元素;参数二:索引; 参数三:当前数组。

this:可选,执行会掉时候,this的指向。

区别:

1、forEach()返回值是undefined,不可以链式调用。

2、map()返回一个新数组,原数组不会改变。

3、没有办法终止或者跳出forEach()循环,除非抛出异常,所以想执行一个数组是否满足什么条件,返回布尔值,可以用一般的for循环实现,或者用Array.every()或者Array.some();

4、$.each()方法规定为每个匹配元素规定运行的函数,可以返回 false 可用于及早停止循环。

下面写一些例子和项目中用到的:

forEach用法:

var data = [1, 2, 3, 4];

data.forEach((item,index) => {
    console.log(data,index);
    if(item === 2){
        data.shift()    // 删除数组的第一个元素
    }
})

输出结果

 [1, 2, 3, 4] 0
 [1, 2, 3, 4] 1
 [2, 3, 4] 2

map用法:

var data = [1, 2, 3, 4];

var arr = data.map((item,index)=>{
    console.log(data,index);
    if(item === 2){
        data.shift()
    }
})
console.log(arr)

输出:

 [1, 2, 3, 4] 0
 [1, 2, 3, 4] 1
 [2, 3, 4] 2
 [undefined, undefined, undefined, empty]

可以看出两者的区别
当然vue项目也常用到

let data = [1,2,3,4];
let arr = data.map(item => {
   return {
        label: item,
        value: ''        
    } 
})
console.log(arr)

输出:

[
    {label: 1, value: ""},
    {label: 2, value: ""},
    {label: 3, value: ""},
    {label: 4, value: ""}
]

 

posted @ 2019-06-05 13:53  望兰鸟  阅读(33663)  评论(0编辑  收藏  举报