Answer the question
In order to leave comments, you need to log in
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)
( 1 )
and ( 2 )
those marked with comments in the code return undefined
? After all, if you look at the method reduce
call in the call under the number ( 3 )
, the construction is similar, BUT working, unlike the first two! In fact, we write in bisOne
and bisTwo
! Please explain why and how it does NOT work!
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question