簡體   English   中英

如何定義關聯數組?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM