0

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)?

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

I have tried so many ways! Thanks a lot.
Accept the answer if you like it :) JavaScript is a weird beast but pretty cool when you get the right mindset for it
1

In google apps script you can also call functions by name

function executeFunctionByName(func) {
  this[func]();
}

4 Comments

Thx Cooper ... Something weird: it's ok if I write the function as follows function myFunc(x) { Browser.msgBox(x * 2); }, and it doesn't work if function is written as const myFunc = function (x) { Browser.msgBox(x * 2) }! Do you have an explanation?
What does that have to do with my answer?
I tried your suggestion. Unfortunately, I couldn't achieve the expected result with my definition of the functions (see the posted request) until I changed them. That's all! But I also remember this one. Upvoted.
I run all kinds of functions this way all of the time. I search for them in my new development files and load them into a drop down in my side bar thus allowing me to easily run new functions from the sidebar.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.