ARUN P.S
ARUN P.S

Reputation: 1723

Loop through all defined variables jquery

Hi I want to loop through all defined variables in a jquery function for pushing corresponding variable name into an array. The code is given below

 function pushallvariables()
 {
    var list = [];

    var name = /^[A-Za-z\s.]+$/;
    var general = /^[A-Za-z0-9\s.\-\/]{2,20}$/;
    var email = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/;
    var digit = /^[+]?[0-9\s]+$/;

      list.push('name');
      list.push('general');
      list.push('email');
      list.push('digit');
 }

I want to modify this function into

 function pushallvariables()
 {
    var list = [];

    var name = /^[A-Za-z\s.]+$/;
    var general = /^[A-Za-z0-9\s.\-\/]{2,20}$/;
    var email = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/;
    var digit = /^[+]?[0-9\s]+$/;

    for each(variable as var)
    {
       list.push(var.name);
    }
  }

But the modified function is not correct. How can I write the function ?

Upvotes: 0

Views: 116

Answers (1)

hsz
hsz

Reputation: 152266

The best and clear way to do that is:

var list = {};

list.name    = /^[A-Za-z\s.]+$/;
list.general = /^[A-Za-z0-9\s.\-\/]{2,20}$/;
list.email   = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/;
list.digit   = /^[+]?[0-9\s]+$/;

without loops, etc

Upvotes: 4

Related Questions