JavaScript forEach 方法不适用于箭头函数
JavaScript forEach method not work with Arrow Function
const array3 = [5, 10, 15, 20, 25, 30, 35, 40];
const function5 = (index, element) => {return index + ": " + element};
console.log(array3.forEach(function5));
为什么这段代码不起作用,我做错了什么?
你需要使用.map()
因为.forEach()
会return你总是undefined
,并且你期望的结果可以通过使用map()
函数获得:
const array3 = [5, 10, 15, 20, 25, 30, 35, 40];
const function5 = (index, element) => {return index + ": " + element};
console.log(array3.map(function5));
你需要Array#map
。这returns一个新数组。
const
array3 = [5, 10, 15, 20, 25, 30, 35, 40],
function5 = (index, element) => index + ": " + element;
console.log(array3.map(function5));
const array3 = [5, 10, 15, 20, 25, 30, 35, 40];
const function5 = (index, element) => {return index + ": " + element};
console.log(array3.forEach(function5));
为什么这段代码不起作用,我做错了什么?
你需要使用.map()
因为.forEach()
会return你总是undefined
,并且你期望的结果可以通过使用map()
函数获得:
const array3 = [5, 10, 15, 20, 25, 30, 35, 40];
const function5 = (index, element) => {return index + ": " + element};
console.log(array3.map(function5));
你需要Array#map
。这returns一个新数组。
const
array3 = [5, 10, 15, 20, 25, 30, 35, 40],
function5 = (index, element) => index + ": " + element;
console.log(array3.map(function5));