博主:DongJiang
码龄:7年
等级:LV.22级
内容:316
今日访问:2312
访问总量:5936
博客简介:学习与分享
博客创建时间:2018-04-12
博客主页 立即前往
赞助位
成为赞助商

map 和 forEach 的都可以用来遍历,它们有什么区别

来源: 2024-05-17 19:25:50 播报

map 和 forEach 的区别是map返回一个新的数组,forEach返回undefined。

使用场景:修改或返回新数组使用map,相反只是做遍历循环时用foreach 或 for

const array = [1, 2, 3, 4, 5]
const arr = array.forEach(x => x * x)
const arr2 = array.map(x => x * x)
console.log(array)  // [1, 2, 3, 4, 5]
console.log(arr)  // undefined
console.log(arr2)  //[1, 4, 9, 16, 25]
原文出处:
版权声明:本文来源地址若非本站均为转载,若侵害到您的权利,请及时联系我们,我们会在第一时间进行处理。