0

So i want to declare variable according to my loop. so i have done the following

 $.each(filter,function(key,value){
    var value;
   });

my filter array contains:

Geo_Name_date,Geo_Gender_date,Geo_Age_date,Geo_Ethnicity_date,Geo_Race_date,Geo_Language_date,Geo_Smoker_ind_date,Geo_Primarycare_provider_name_date  

When i alert after the loop over. the variable should alert undefined. But its giving reference error. any suggestion or what am doing wrong? is it possible to do like this?

divakar
  • 1,379
  • 6
  • 15
  • 31

2 Answers2

1

To assign a global variable, leave out the var keyword:

$.each(filter, function(key, value) {
    globalValue = undefined;
});
alert(globalValue); // Will show undefined
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Hey Barmar, So i have tried something like this but it not seems to be working. $.each(filter,function(key,value){ value=undefined; }); alert(Geo_Name_date); – divakar Sep 25 '14 at 07:03
1

You should preferably create properties in an object rather than global variables:

var values = {};
$.each(filter, function(key, value) {
  values[value] = undefined;
});

It's possible to create global variables dynamically. You should avoid creating a lot of variables in the global scope, but if that is really what you need, you can use the eval method to assign values to the variables in the loop without declaring them. That will create them in the global scope:

$.each(filter, function(key, value) {
  eval(value + '=undefined');
});
Guffa
  • 687,336
  • 108
  • 737
  • 1,005