Reputation: 393
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);
}
Upvotes: 1
Views: 57
Reputation: 386746
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);
}
Upvotes: 5