red house 87
red house 87

Reputation: 2415

Dynamically setting variables in javascript

Trying to dynamically set variables depending how many vimeo iframes are on my page. Im using the Eval method in my code below:

var numberVimeoFrames = jQuery(".vimeo").length;

for(i=1;i<=numberVimeoFrames;i++){
    var refFrame = jQuery('.vimeo:nth-child(' + i + ')');
    eval("player" + i + "= new Vimeo.Player(" + refFrame + ")");
}

My eval line is however generating an error message:

Uncaught SyntaxError: Unexpected identifier

To me it looks like ive concatenated correctly so not sure where ive gone wrong?

Upvotes: 1

Views: 69

Answers (1)

M0nst3R
M0nst3R

Reputation: 5283

Even though in this case I do not think it is that bad, the general opinion is to not use eval at all. Use arrays instead :

var numberVimeoFrames = jQuery(".vimeo").length;

var players = [];
for(i=1;i<=numberVimeoFrames;i++){
    var refFrame = jQuery('.vimeo:nth-child(' + i + ')');
    players.push(new Vimeo.Player(refFrame));
}

You can now access your players by calling the array (for example players[1] instead of player1 and so on.)

Upvotes: 1

Related Questions