简体   繁体   中英

Why this forEach mapping is undefined?

Why the result for this forEach mapping is undefined?

const list = [1, 2, 3, 4, 5, 6, 7];
const result = list.forEach(a => a % 2 === 0 ? a : -a);
console.log(result); // console prints undefined

forEach does not return anything. So you are getting undefined. In this case you can use map which will return an array

 const list = [1, 2, 3, 4, 5, 6, 7]; const result = list.map(a => a % 2 === 0 ? a : -a); console.log(result)

forEach为列表中的每个成员运行一个操作,如果您想要一个包含基于表达式的值的新列表,您应该使用map

Foreach doesnt collect results of the function you pass it, you need to use map for that!

const list = [1, 2, 3, 4, 5, 6, 7];
const result = list.map(a => a % 2 === 0 ? a : -a);
console.log(result);

It is because the forEach doesn't return a new object, then it is undefined. If you want a return you should use .map.

I would add that forEach is used to perform a function that does return something on each item in an array, so you could do the following:

const list = [1, 2, 3, 4, 5, 6, 7];
const result = list.forEach(a => console.log(a % 2 === 0 ? a : -a));

however if you need a new array with the computed results, map is the better solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM