循环遍历所有已定义的变量jquery

时间:2014-01-27 08:42:56

标签: javascript jquery

您好我想循环遍历jquery函数中的所有已定义变量,以将相应的变量名称推送到数组中。代码如下:

 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');
 }

我想将此功能修改为

 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);
    }
  }

但修改后的功能不正确。我该怎么写这个函数?

1 个答案:

答案 0 :(得分:4)

最好和最明确的方法是:

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]+$/;

没有循环等