Javascript: Passing Functions

I am learning javascript. I know that we can pass a function to other functions after defining a function. But I need help understanding this example:

function map(func, array) { var result = []; forEach(array, function (element) { result.push(func(element)); }); return result; } 

From what I can understand, func is a map argument. I need to provide func function. But in the textbook that I am reading, he does not mention where this function came from, it seems there is no need to indicate this argument? Another example in the tutorial is the same:

  function count(test, array) { return reduce(function(total, element) { return total + (test(element) ? 1 : 0); }, 0, array); } 

Is this test function equal to === 0? 1: 0, but the tutorial does not say that I need to write a test function. Do I need to write this test function?

+6
source share
2 answers

EDIT: In the tutorial link that you posted, the function passed is a predefined function of Math.round . My example below shows how to create your own function.


The map example shows an implementation. You must provide a function (and an array) when you call map .

In appearance, map passes the current element to the Array of your function, and your function must do something with it and return a result. The results returned by your function are added to the new array.

 var arr = [1,2,3,4,5]; var my_func = function(item) { return item * 2; }; var new_arr = map(my_func, arr); console.log(new_arr); // [2,4,6,8,10] 
  • we created an array ( arr ),

  • we created a function ( my_func ) that takes what it gives and multiplies it by 2.

  • we passed both values ​​to map

  • The map function iterates through our arr , passing the current element in each iteration of our function.

  • our function takes the current element and returns the result of multiplying by 2.

  • The map function takes this result and adds it to the new array.

  • when the iteration is complete, the map function returns a new array.

+4
source

When you call a map, you pass in a built-in function or an existing function.

 // The following would return [2,3,4] map(function(item) { return item + 1}, [1,2,3]); function double(item) {return item*2} map(double, [1,2,3]) // returns [2,4,6] // Your example, Math.round map(Math.round, [0.01, 2, 9.89, Math.PI]) // returns [0,2,10,3] 

Another way of saying that a function can be passed to another function is like any other argument. It is on the same lines that a function, like any other variable, can be passed or returned from a function

 function createAdder(toAdd) { return function (num) { return num + toAdd; } } var add5 = createAdder(5); add5(2); // returns 7 var add7 = createAdder(7); add7(-2); // returns 5 
0
source

Source: https://habr.com/ru/post/918224/


All Articles