I have this object:
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;
}
}
Its used in this way:
var cForm=new formBuddy();
cForm.addField("c_first_name","First Name","required");
cForm.addField("c_last_name","Last Name","required");
The problem is, in the addField()
function the fields
array is being set correct (perhaps because a numerical index is being used to refer to it) but the other 2 arrays (labels
and rules
) aren't being touched at all. Doing a console.log
shows them as empty in firebug.
What do I need to change to make them work? I'd still like to refer to the rules and labels by the string index of the field.
Arrays are treated as Objects in Javascript, therefore your piece of code works, it's just that firebug's
console.log
isn't showing you the "Objects" inside the array, rather just the array values ...Use the
for(var i in obj)
to see what objects values the Array contains:fields
should be an array, whereaslabels
andrules
should be objects as you want to use strings as keys. Also,addField()
is the same for each instance ofFormBuddy()
(names of constructor functions should be capitalized) and should reside in the prototype, ieYou can access the labels/rules via
Just to further enrage Luca ;), here's another version which also dosn't encapsulate anything:
It's similar to Gumbo's second version, but his
fields
object is merged into theFormBuddy
instance. An array calledfields
is added instead to allow for fast iteration.To access a field's label, rule, or id, use
To iterate over the fields, use
Use objects instead:
But as Christoph already mentioned, I would store this information in a single data structure too. For example: