1

I am trying to use functions from an object, but having no success.

let ops = [
    {'*': (a, b) => a * b}, 
    {'/': (a, b) => a / b},
    {'+': (a, b) => a + b},
    {'-': (a, b) => a - b}
];

let res = [];
let current;

for (var i = 0; i < ops.length; i++) {
   current = ops[i];
   res = current(4, 2);
   console.log(res);
}
falinsky
  • 7,229
  • 3
  • 32
  • 56
user6642297
  • 395
  • 3
  • 19

1 Answers1

5

Without changing ops, you need to take the function out of the object by getting all values of the object and take the first one.

 let ops = [
    {'*': (a, b) => a * b}, 
    {'/': (a, b) => a / b},
    {'+': (a, b) => a + b},
    {'-': (a, b) => a - b}
];

let res = [];
let current;

for (var i = 0; i < ops.length; i++) {
   current = Object.values(ops[i])[0];
   res = current(4, 2);
   console.log(res);
}

A smarter approach is to use only the functions in an array.

 let ops = [
        (a, b) => a * b, 
        (a, b) => a / b,
        (a, b) => a + b,
        (a, b) => a - b
    ];

let res = [];
let current;

for (var i = 0; i < ops.length; i++) {
   current = ops[i];
   res = current(4, 2);
   console.log(res);
}
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392