首页 > 解决方案 > JavaScript forEach 方法不适用于箭头函数

问题描述

const array3 = [5, 10, 15, 20, 25, 30, 35, 40];
const function5 = (index, element) => {return index + ": " + element};
console.log(array3.forEach(function5));

为什么这段代码不起作用,我做错了什么?

标签: javascriptforeacharrow-functions

解决方案


您需要使用.map()as.forEach()将始终返回您undefined,并且可以通过使用map()函数获得您期望的结果:

const array3 = [5, 10, 15, 20, 25, 30, 35, 40];
const function5 = (index, element) => {return index + ": " + element};
console.log(array3.map(function5));


推荐阅读