forEach()和map()的區(qū)別?【專欄09】

相同點:
都是循環(huán)遍歷數(shù)組中的每一項 每次執(zhí)行匿名函數(shù)參數(shù)一樣,分別是item(當前每一項)、index(索引值)、arr(原數(shù)組) 只能遍歷數(shù)組 匿名函數(shù)中的this都是指向window; 兩種方法都不能用 break 中斷
const users = ["鬼鬼", "劉亦菲", "周星馳"];
users.forEach((item, index, arr) => {
console.log(item, index, arr);
},this);
const users = ["鬼鬼", "劉亦菲", "周星馳"];
users.map((item,index,arr)=>{
console.log(item,index,arr)
},this)
不同點:
map()速度比forEach()快; map()會返回一個新數(shù)組,不對原數(shù)組產(chǎn)生影響; map()方法輸出可以與其他方法(如reduce()、sort()、filter())鏈接在一起
性能對比
const users=new Array(10000).fill("鬼鬼");
// 1. forEach()
console.time("forEach");
const newArray = [];
users.forEach((item) => {
newArray.push(item)
});
console.timeEnd("forEach");
// 2. map()
console.time("map");
const newArray2 = users.map ((item) => {
return item
});
console.timeEnd("map");
差距還是挺大的

參考資料
https:/cnblogs.com/kaiqinzhang/p/11496151.html
說明
本專欄總共匯總了
150道題,每道題目答案沒有多余扯皮的部分,就是單純的答案。關(guān)注公眾號,每天一到面試題,為下次跳槽準備,人人都能沖擊
30k+,點擊↓關(guān)注【鬼哥】當前進度【#009題】,如果你能點贊分享、鬼哥騎自行車也是開心的
評論
圖片
表情
