Joe
Joe

Reputation: 457

How to pass an integer to create new variable name?

I have 50 svg animations named animation0, animation1, animation2 etc. and I want to load them when the integer 0 to 49 is passed to this function:

function loadAnimation(value){
    var whichswiffy = "animation" + value;
    var stage = new swiffy.Stage(document.getElementById('swiffycontainer'), whichswiffy);
    stage.start();
}

It doesn't work at the moment, maybe it's passing 'whichswiffy' rather than animation10?

Any ideas?

Upvotes: 0

Views: 433

Answers (2)

user1106925
user1106925

Reputation:

"I have 50 svg animations named animation0, animation1, animation2 etc."

Using global variables

I assume this means you have variables. If they're global variables, you can access them as a property of the global object.

var whichswiffy = window["animation" + value];

Using an Object instead of variables

But if they're not global variables (or even if they are), you'd be better off storing them in an Object...

var animations = {
    animation0: your first value,
    animation1: your second value,
    /* and so on */
}

...and then access them as properties of that object...

var whichswiffy = animations["animation" + value];

Using an Array instead of variables

Or better, just use an Array since the only differentiation is the number...

var animations = [
    your first value,
    your second value,
    /* and so on */
]

then just use the index...

var whichswiffy = animations[value];

Upvotes: 5

xdazz
xdazz

Reputation: 160833

If your variables are global, you could do

var stage = new swiffy.Stage(document.getElementById('swiffycontainer'), window[whichswiffy]);

Upvotes: 2

Related Questions