1

Hi I am trying to make dynamic variables but it is saying `variable v0 (through to v5) is not defined.

td.each(function(i){
eval('var v' + i + ' = \'' + $(this).html() + '\';' );
});

any help would be muchly appreciated.

alex
  • 479,566
  • 201
  • 878
  • 984
Phil Jackson
  • 10,238
  • 23
  • 96
  • 130

2 Answers2

4

That sounds like a bad idea.

Is there any reason you can't do this?

var tdHtml = td.map(function() { return $(this).html(); }).get();
alex
  • 479,566
  • 201
  • 878
  • 984
  • seeing as `i` will be a zero-based index, one might as well declare `tdHtml` as `[]`, since this is exactly the use that arrays were intended for. – David Hedlund Dec 08 '10 at 07:31
  • @David Hedlund Ah yeah, I changed how it works and forgot to change the starting literal. Cheers. – alex Dec 08 '10 at 07:31
4

Oh my.

If you want to create a global "dynamic variable" you should not use var. In this context it creates a variable that is local inside of the each-function, which is quite useless (and will cause it to be undefined outside of the loop, which is what you're experiencing). Instead you should do it like this:

td.each(function(i){
  window['v' + i] = $(this).html();
});

The downside with the above code is that global variables are not really great either.

On the other hand, if you want a local variable (if for example there will be more code in the loop that uses this varaible, then I would do it like this:

td.each(function(i){
  var dynVars = {};
  dynVars['v' + i] = $(this).html();

  alert(dynVars.v4); // use the dynamic variables by saying "dynVars.NAME"

});

You could combine these two solutions, by putting the declaration of dynvars (var dynVars = {}) in the scope where you want to be able to access your variables instead. As long as it is also visible in this each-callback, everything will work out fine.

Jakob
  • 24,154
  • 8
  • 46
  • 57