user6642297
user6642297

Reputation: 393

How can I use the object's functions in pure JavaScript, without using jquery?

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

Answers (1)

Nina Scholz
Nina Scholz

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

Related Questions