我有这个对象:
function formBuddy() { var fields = new Array(); var labels = new Array(); var rules = new Array(); var count=0; this.addField = function(field, label, rule) { fields[count] = field; labels[field] = label; rules[field] = rule; count = ++count; } }
它以这种方式使用:
var cForm=new formBuddy(); cForm.addField("c_first_name","First Name","required"); cForm.addField("c_last_name","Last Name","required");
问题是,在addField()
函数中,fields
数组设置正确(可能是因为数字索引用于引用它),但其他2个数组(labels
和rules
)根本没有被触及.做一个console.log
在firebug中显示为空的.
我需要改变什么来使它们工作?我仍然想通过字段的字符串索引来引用规则和标签.
改为使用对象:
function formBuddy() { var fields = {}; var labels = {}; var rules = {}; var count = 0; this.addField = function(field, label, rule) { fields[count] = field; labels[field] = label; rules[field] = rule; count++; } }
但正如Christoph已经提到的那样,我也会将这些信息存储在一个数据结构中.例如:
function formBuddy() { var fields = {}; this.addField = function(name, label, rule) { fields[name] = { name: name, label: label, rule: rule }; }; this.getField = function(name) { return fields[name]; }; } var cForm=new formBuddy(); cForm.addField("c_first_name","First Name","required"); cForm.addField("c_last_name","Last Name","required"); alert(cForm.getField("c_last_name").label);