user3821345
user3821345

Reputation: 648

Javascript pass variable to function name

I’m trying to create a simple loop of animation functions. I've stored their names in an array and am able to log out each object as a string with a click event. However I can't seem to call the corresponding functions of that event

I've tried to do this but I get an error nt[rt] is not a function

arrAnimations[activeScene]()

I've tried many approaches from stack overflow from similar questions, such as creating a helper function like this

myFunction = function(){};   
var arrAnimations = {italy: myFunction};

arrAnimations['activeScene']();//executes the function

and this

var tmp = arrAnimations[activeScene]
window[tmp]

Here is the code:

var arrAnimations = [
  'italy',
  'czech',
  'russia'
]

var activeScene = 0;

document.getElementById('animate').addEventListener("click",
  function incNumber() {
      if (activeScene < arrAnimations.length - 1) {
          activeScene++;
      } else if (activeScene = arrAnimations.length - 1) {
          activeScene = 0;
      }
      // console.log(arrAnimations[activeScene])
  }
)

function italy() { console.log('italy') }

function czech() { console.log('czech') }

function russia() { console.log('russia') }
<div id="animate">Animate</div>

Upvotes: 1

Views: 1727

Answers (4)

Mubeen Khan
Mubeen Khan

Reputation: 1067

italy = () => console.log('italy')
czech = () => console.log('czech')
russia = () => console.log('russia') 

if Array of functions:

let arrAnimationsAsFunctions = [ italy , czech , russia];
arrAnimationsAsFunctions.forEach(animation => animation())

if Array of Strings:

let arrAnimationsAsStrings = [ 'italy' , 'czech' , 'russia' ];
arrAnimationsAsStrings.forEach(animation => eval(animation)())

use eval to run a string as JS code

Upvotes: 1

clint
clint

Reputation: 301

In your commented out line:

console.log(arrAnimations[activeScene])

You're trying to call a method on the array, which doesn't exist. It's an array of strings. Instead, you need to get the string value, then use that to call a method on the window.

window[arrAnimations[activeScene]]();

With that said though, I'd make your code a bit simpler and use lambda functions, and avoid a couple of if statements, try this:

<div id="animate">Animate</div>

<script>
    var arrAnimations = [
        () => console.log('italy'),
        () => console.log('czech'),
        () => console.log('russia')
    ]

    var activeScene = 0;

    document.getElementById('animate').addEventListener('click', () => {

        arrAnimations[activeScene]();

        activeScene++;
        activeScene = activeScene % arrAnimations.length;
    });
</script>

Upvotes: 1

KyleMit
KyleMit

Reputation: 29947

The array can store the actual functions themselves, instead of the function names.

function italy()  { console.log('italy') }
function czech()  { console.log('czech') }
function russia() { console.log('russia') }

var arrAnimations = [ italy, czech, russia ]

Then locate the item in the array, and call it:

var activeScene = 0;
arrAnimations[activeScene]()

Demo in Stack Snippets

function italy()  { console.log('italy') }
function czech()  { console.log('czech') }
function russia() { console.log('russia') }

var arrAnimations = [ italy, czech, russia ]

var index = 0;

function callNextFunction() {
    index = index >= arrAnimations.length - 1 ? 0 : index + 1
    
    arrAnimations[index]()
}

var btn = document.getElementById('animate')
btn.addEventListener("click", callNextFunction)
<button id="animate">Animate</button>

Upvotes: 1

sfy
sfy

Reputation: 3238

Is this what you want?

foo = () => console.log('foo')
bar = () => console.log('bar')
baz = () => console.log('baz')

fns = {
  foo,
  bar,
  baz
}

Object.keys(fns).forEach(fn => fns[fn]())

fns['foo']()
fns['bar']()

Note: you can't cast a string to a function like this, at least in Javascript:

let fn = () => {}
let foo = 'fn'
foo()  // X
// foo is a string, not a function, It is just a coincidence that the content of the string is same with the function's name

Upvotes: 0

Related Questions