function copyArrayAndManipulate(array, instructions) {
return array.map(function (element, index, arr) {
return arr.push(instructions(element));
});
}
function multiplyBy2(input) {
return input * 2;
}
var result = copyArrayAndManipulate([1, 2, 3], multiplyBy2);
console.log(result)
I do not know why result equals to [4,5,6], i debugged it but i can't see the value 5 even while debugging. Just trying to understand how this [4,5,6] array came from, not asking for some solution.
CodePudding user response:
map
method will return you a new array. So you should not push to arr
inside map
method. You already get multiplied array
function copyArrayAndManipulate(array, instructions) {
return array.map(function (element, index, arr) {
return instructions(element); // you should not push
});
}
function multiplyBy2(input) {
return input * 2;
}
var result = copyArrayAndManipulate([1, 2, 3], multiplyBy2);
CodePudding user response:
You are basically rewriting map
using map
. map
already does what you call copyArrayAndManipulate
, so it seems like a useless wrap around a function that already exists. If you want your code to work, you simply need to remove arr.push
and just return instructions(element)
within the map
function. The map
function will return a new "copy" of the array and "manipulate" the array with the function you give it, passing you the each "element".