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
  • 6,722
  • 3
  • 30
  • 53
user6642297
  • 260
  • 2
  • 16

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
  • 351,820
  • 24
  • 303
  • 358