M
M
Muranx2019-05-09 10:15:00
JavaScript
Muranx, 2019-05-09 10:15:00

Why doesn't the forEach( ) method work?

var bisOne = [1,2,3,4,5].forEach(function(e,i,arr){return arr[i]=e*10}); 
var ghost = [1,2,3,4,5]
var bisTwo = ghost.forEach(function(e,i,arr){return arr[i]=e*10}) 

console.log(bisOne);  //(1)
console.log(ghost);
console.log(bisTwo);  //(2)

var gsp=[1,2,3,4,5].reduce(function(a,b){return a+b}) 
console.log(gsp);  //(3)

I can’t understand why calls ( 1 )and ( 2 )those marked with comments in the code return undefined? After all, if you look at the method reducecall in the call under the number ( 3 ), the construction is similar, BUT working, unlike the first two! In fact, we write in bisOneand bisTwo! Please explain why and how it does NOT work!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Ukolov, 2019-05-09
@Muranx

Because, all of a sudden, forEach is not the same as reduce . The forEach method is used exclusively for iteration , while reduce is used to get some result , so forEach does not return anything .
You need a map method :
If you really want to do this with forEach, then it should be like this:

var bisOne = [1,2,3,4,5];
bisOne.forEach(function(e,i,arr){arr[i]=e*10});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question