js 世界

【面试题】.forEach() 和 .map()的使用及区别是什

2022-08-06  本文已影响0人  前端末晨曦吖

.forEach() 和 .map()的使用及区别是什么?

点击打开视频教程

forEach()和map()方法通常用于遍历Array元素

定义

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>

总结:

上一篇下一篇

猜你喜欢

热点阅读