Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to call a function stored in an array

I have this simple example that works

const func1 = function (i) { return (i) }
const func2 = function (i) { return (i * 2) }
const func3 = function (i) { return (i * 3) }
const func4 = function (i) { return (i * 4) }
const funcs = ['func1', 'func2', 'func3', 'func4']

function myFunction() {

  let item = 3
  let i = 2
  let result = eval(`${funcs[item]}(${i})`)
  console.log(result)
  // what about call_user_func in google app script

}

Since eval() is not recommended, what will be the google app script equivalent of call_user_func (php)?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I’m unfamiliar with Google Apps Script but in standard JS you should just be able to call it like let result = funcs[item](i);

For this you also need to put your actual function variables into the array, like
const funcs = [func1, func2, func3, func4], not like const funcs = ['func1', 'func2', 'func3', 'func4']

Functions are first-class citizens in JS, which means you can pass them around and call them like any other variable

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading