using forEach to apply a function to each array item in javascript -
I am trying to understand how everything works in Java
var Arr = [5, 4,3,2,1]; Var class = function (x) {return x * x; } Arr.forEach (function (item) {item = class (item);});
I should get the [25, 16, 9, 4, 1]
. But get [5, 4, 3, 2, 1]
The item
is an argument for your callback function (which works like a local variable) and modifying it does not change the array - this is not the actual array element. For the callback, the next two arguments give you the array and Indexes so that you can modify the actual array element.
var arr = [5,4,3,2,1]; Var class = function (x) {return x * x; } Arr.forEach (function (item, index, array) {array [index] = square (item);});
Working demo:
You may want to keep in mind that .map ()
create a new array for the operation Created for example:
var arr = [5,4,3,2,1]; Var class = function (x) {return x * x; } Var newArray = arr.map (class);
Working demo:
Comments
Post a Comment