【面试题】.forEach() 和 .map()的使用及区别是什
2022-08-06 本文已影响0人
前端末晨曦吖
.forEach() 和 .map()的使用及区别是什么?
forEach()和map()方法通常用于遍历Array元素
定义
- forEach(): 针对每一个元素执行提供的函数(executes a provided function once for each array element)。除了抛出异常以外,没有办法中止或跳出 forEach() 循环。如果你需要中止或跳出循环,forEach() 方法不是应当使用的工具。
- map(): 创建一个新的数组,其中每一个元素由调用数组中的每一个元素执行提供的函数得来(creates a new array with the results of calling a provided function on every element in the calling array)。map 方法会给原数组中的每个元素都按顺序调用一次 callback 函数。callback 每次执行后的返回值(包括 undefined)组合起来形成一个新数组。 callback 函数只会在有值的索引上被调用;那些从来没被赋过值或者使用 delete 删除的索引则不会被调用。
forEach()方法
参数:item数组中的当前项,index当前项的索引,第三个参数原始数组;
案例:
<template>
<div id="app">
<button @click="getForEach">forEach方法</button>
</div>
</template>
<script>
export default {
name: 'App',
data(){
return {
}
},
mounted(){
},
methods:{
getForEach(){
const numbers = [1, 2, 3, 4, 5];
// 使用 forEach()
//基本使用
numbers.forEach((item,index,data) => {
console.log(item,index,data)
})
//forEach返回值是什么呢?是否有返回值?
let res = numbers.forEach((item,index,data) => {
console.log(item,index,data)
})
console.log('返回值',res); // undefined
//forEach方法会不会更改原数组呢?或者怎么改变原数组呢?
let list = [
{ id:1,name:'末晨曦吖' },
{ id:2,name:'黎明前的黑暗' },
]
list.forEach((item,index,data) => {
if(item.id == 1){
item.name = '风带不走落寞' //可以更改原数组
// item = { id:1,name:'风带不走落寞' } //不可以更改原数组
}
})
console.log('是否更改原数组',list);
}
}
}
</script>
<style scoped>
</style>
map()方法
参数:item数组中的当前项,index当前项的索引,第三个参数原始数组;
<template>
<div id="app">
<button @click="getMap">map方法</button>
</div>
</template>
<script>
export default {
name: 'App',
data(){
return {
}
},
mounted(){
},
methods:{
getMap(){
const array = [12,24,27,23,26];
const res = array.map((item,index,data) => {
data[index] = item*10; //可更改原数组,但返回值全部为undefined
// return item * 2
})
console.log('原数组',array);
console.log('改变后的数组',res);
}
}
}
</script>
<style scoped>
</style>
由于forEach()返回undefined,所以我们需要传递一个空数组来创建一个新的转换后的数组。map()方法不存在这样的问题,它直接返回新的转换后的数组。在这种情况下,建议使用map()方法。
链接其他方法
map()方法输出可以与其他方法(如reduce()、sort()、filter())链接在一起,以便在一条语句中执行多个操作。
另一方面,forEach()是一个终端方法,这意味着它不能与其他方法链接,因为它返回undefined。
<template>
<div id="app">
<button @click="getMapLink">链接其他方法</button>
</div>
</template>
<script>
export default {
name: 'App',
data(){
return {
}
},
mounted(){
},
methods:{
getMapLink(){
const array = [12,24,27,23,26];
const res = array.map((item,index,data) => {
return item
}).reduce((total, value) => total + value)
console.log(res);
},
}
}
</script>
<style scoped>
</style>
总结:
- forEach()方法不会返回执行结果,而是undefined。forEach() 被调用时,不会改变原数组,也就是调用它的数组(尽管 callback 函数在被调用时可能会改变原数组)。
- map()方法会分配内存空间存储新数组并返回,map 不修改调用它的原数组本身(当然可以在 callback 执行时改变原数组)。