简体   繁体   中英

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> 

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> 

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM