[英]How do I define an associative array?
我想定义自己理解的是一个关联数组(或对象),这样我就有类似以下的条目:“ Bath” = [1,2,5,5,13,21]“ London” = [4, 7,13,25]
我尝试了以下方法:
var xref = new Object;
xref = [];
obj3 = {
offices: []
};
xref.push(obj3);
然后使用
xref[name].offices.push(number);
但是我收到“ TypeError:xref [name]未定义”。 我究竟做错了什么 ?
像使用obj3一样使用对象:
var xref = {};
xref.obj3 = obj3;
var name = 'obj3';
xref[name].offices.push(number);
var obj = {
arr : [],
}
var name = "vinoth";
obj.arr.push(name);
console.log(obj.arr.length);
console.log(obj.arr[0]);
obj.prop = "Vijay";
console.log(obj.prop);
您可以使用object literal
。
我意识到,我真正想要的只是一个二维数组,其中第一维是键(即“ BATH”,“ LONDON”),第二维是交叉引用列表(即1,2,5,5) ,13,21)-所以我还不需要了解对象路由! 其他建议可能会很好地起作用,并且“更纯正”,但二维数组更适合我的老式大脑使用。
所以我做了以下事情:
var xref = [];
// go through source arrays
for (i = 0; i < offices.length; i++) {
for (j = 0; j < offices[i].rel.length; j++) {
// Check if town already exists, if not create array, then push index
if (xref[offices[i].rel[j].town] === undefined) {
xref[offices[i].rel[j].town] = [];
alert('undefined so created '+offices[i].rel[j].town);
};
xref[offices[i].rel[j].town].push(i); // Add index to town list
};
};
我相信通过阅读其他文章,如果将“ offices [i] .rel [j] .town”中的任何一个设置为undefined,但数据没有这种可能性,我将遇到问题。
现在,我可以通过执行以下操作来访问交叉引用列表:
townlist = "";
for (i = 0; i < xref["BATH"].length; i++) {
townlist += offices[xref["BATH"][i]].name+' ';
};
alert(townlist);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.