简体   繁体   中英

How to call a function Multiple times

Here is the code snippets

let sum = a => b => b ? sum(a + b) : a;
console.log(sum(10)(20)(3)(4)());

So we are calling the sum function 5 times But let's assume we have an array of any length which contains only numbers

let arrayValue = [1,2,3,4,5,...];

now I want to call the sum function to the length of that array where the last call should be () as it does not contain any number;

Desired Output should be sum(1)(2)(3)(4)(5)() and this will generate programmatically depending on the length of the array

If you look at

console.log(sum(10)(20)(3)(4)());

It's basically doing this:

const x1 = sum(10);
const x2 = x1(20);
const x3 = x2(3);
const x4 = x3(4);
const x5 = x4();
console.log(x5);

So the question is: How do we do that from this starting point?

let arrayValue = [1,2,3,4,5];

The answer is either a loop or recursion. A loop is simple enough, so let's do that:

let x = sum;
for (const value of arrayValue) {
    x = x(value);
}
x = x();
console.log(x);

 let sum = a => b => b ? sum(a + b) : a; function example(arrayValue) { let x = sum; for (const value of arrayValue) { x = x(value); } x = x(); console.log(arrayValue.join(", "), "=>", x); } example([10, 20, 3, 4]); example([1, 2, 3, 4, 5]);

We start by setting x to sum (the function, not a call to it), then for each array value we call whatever function x currently refers to passing in the value and storing the return value back in x again. When we run out of values, we call the result with no argument.

You can loop over to the length of the array. You can use .length property to do this and then call your function inside the loop.

Example:

let arrayValue = [1, 2, 3, 4, 5 , …];

for (let i = 0; i < arrayValue.length; i++) {
  someFunction(arrayValue[i]);
}

Reference : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/length

I hope this is what you are looking for.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM