Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get values from inner function

I need to get values(arr, sum) from inner function fn. i try to push it to results array in outer function or try to assign it like this a = fn();, no go. What i do wrong and how do i get this values in outer function?

    function func(limit) {
      let results = [];
      let arr = [];

      console.log(limit);
      function fn() {
        let arg = arguments;
        let sum = 0;
        for (let i = 0; i < arg.length; i++) {
          sum += arg[i];
          arr.push(arg[i]);
        };
        fn();
        console.log(arr, sum);
        results.push({args: arr, result: sum});
        return sum;
      };
      fn();
      console.log(results);
      return fn;
    };

  const mSum = func(2);
  console.log(mSum(3,4,5));

func returns 12, as intended, but i also need to further work with results array, so i try to use

results.push({args: arr, result: sum});

is you use console.log(arr, sum); you can see its there, but how do put it in aouter function func? in result it pushes keys, but values are empty array and 0.

like image 218
ma_le Avatar asked Aug 15 '26 16:08

ma_le


1 Answers

You could return the object, instead of a single value.

function func(limit) {
  function fn() {
    let arg = arguments;
    let sum = 0;
    for (let i = 0; i < arg.length; i++) {
      sum += arg[i];
      arr.push(arg[i]);
    };
    return { args: arr, result: sum };
  }

  let results = [];
  let arr = [];
  return fn;
};

const mSum = func(2);
console.log(mSum(3, 4, 5));
like image 171
Nina Scholz Avatar answered Aug 17 '26 06:08

Nina Scholz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!