简体   繁体   English

如何定义关联数组?

[英]How do I define an associative array?

I want to define what I understand is an associative array (or maybe an object) such that I have entries like the following: "Bath" = [1,2,5,5,13,21] "London" = [4,7,13,25] 我想定义自己理解的是一个关联数组(或对象),这样我就有类似以下的条目:“ Bath” = [1,2,5,5,13,​​21]“ London” = [4, 7,13,25]

I've tried the following: 我尝试了以下方法:

var xref = new Object;
xref = [];
obj3 = {
      offices: []
      };
xref.push(obj3);

Then cycling through my data with 然后使用

xref[name].offices.push(number);

But I get "TypeError: xref[name] is undefined". 但是我收到“ TypeError:xref [name]未定义”。 What am I doing wrong ? 我究竟做错了什么 ?

Use an object like you do with obj3: 像使用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);

You can use an object literal . 您可以使用object literal

I realised that all I really wanted was a 2 dimensional array with the first dimension being the key (ie. "BATH", "LONDON") and the second being the list of cross-references (ie. 1,2,5,5,13,21) - so I don't need to understand the Object route yet ! 我意识到,我真正想要的只是一个二维数组,其中第一维是键(即“ BATH”,“ LONDON”),第二维是交叉引用列表(即1,2,5,5) ,13,21)-所以我还不需要了解对象路由! The other suggestions may well work and be "purer" but the 2 dimensional array is easier for my old-fashioned brain to work with. 其他建议可能会很好地起作用,并且“更纯正”,但二维数组更适合我的老式大脑使用。

So I did the following: 所以我做了以下事情:

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

I believe from reading other posts that I would have problems if any of the 'offices[i].rel[j].town' were set to undefined but the data doesn't have this possibility. 我相信通过阅读其他文章,如果将“ offices [i] .rel [j] .town”中的任何一个设置为undefined,但数据没有这种可能性,我将遇到问题。

Now I can access a cross-reference list by doing something like: 现在,我可以通过执行以下操作来访问交叉引用列表:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM