在JavaScript关联数组 [英] Associative arrays in javascript
问题描述
我有这样的对象:
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");
问题是,在激活addField()
功能字段
阵列被设置正确(也许是因为数字索引被用来指它),但是其他两个阵列(标签
和规则
)不存在感动的。做一个的console.log
显示他们作为萤火空。
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.
推荐答案
使用对象,而不是:
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++;
}
}
但作为克里斯托夫已经提到,我会存储在一个单一的数据结构,这些信息了。例如:
But as Christoph already mentioned, I would store this information in a single data structure too. For example:
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);
这篇关于在JavaScript关联数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!