2009-12-26 67 views
0

我似乎有一個數組範圍問題。我有一個全局變量;Actionscript 3 array scope/multidimentional array questions

var itemConnect:Array = new Array(); 

哪一個在開始時被初始化。然後,我有一個函數來填充它作爲一個2-d數組:

// Draw connections 
function initConnections() { 
for (var i:Number = 0; i < anotherArray.length; i++) { 
    for (var j:Number = 0; j < anotherArray[i].length; j++) { 
    itemConnect[i] = new Array(); 
    itemConnect[i][j] = new Shape(); 
    } 
} 
} 

的數據結構看起來是這樣的:

CREATE: i = 0, j = 1, val = [object Shape] 
CREATE: i = 0, j = 14, val = [object Shape] 
CREATE: i = 1, j = 2, val = [object Shape] 
CREATE: i = 1, j = 3, val = [object Shape] 
CREATE: i = 1, j = 4, val = [object Shape] 
CREATE: i = 1, j = 5, val = [object Shape] 
CREATE: i = 1, j = 6, val = [object Shape] 
... 

如果我嘗試在其他功能訪問此陣,我只是得到此:

i = 0, j = 14, val = [object Shape] 
i = 1, j = 51, val = [object Shape] 
TypeError: Error #1010: A term is undefined and has no properties. 
at main_fla::MainTimeline/mouseDownHandler() 

我試圖在開始作爲2 d陣列陣列初始化如下:

var itemConnect:Array = new Array(); 
for (var counti = 0; counti < anotherArray.length; counti++) { 
itemConnect[counti] = new Array(); 
} 

將會產生效果會稍好一點,但還惦記着許多節點:

i = 0, j = 14, val = [object Shape] 
i = 1, j = 51, val = [object Shape] 
i = 3, j = 47, val = [object Shape] 
i = 6, j = 42, val = [object Shape] 
i = 7, j = 42, val = [object Shape] 
i = 8, j = 45, val = [object Shape] 
i = 9, j = 42, val = [object Shape] 
... 

它似乎已經到了每一個[我]節點的只是一個範圍的訪問,所以[1] [2] [1] [3],[1] [4]缺失 - 僅出現最後一個[j]元素。

這樣做的正確方法是什麼?我也不知道在開始時陣列的確切大小,這可能是一個問題。

謝謝

回答

0

是不是你的嵌套循環意味着看起來更像這樣?

function initConnections() { 
    for (var i:Number = 0; i < anotherArray.length; i++) { 
     itemConnect[i] = new Array(); 
     for (var j:Number = 0; j < anotherArray[i].length; j++) { 
      itemConnect[i][j] = new Shape(); 
     } 
    } 
} 

注意在這個版本內陣列的構造將會發生,這意味着要被迭代它循環之外。

+0

是;這絕對是一個問題。在你的代碼中,你正在創建新的[i]數組,而不是你想要的。 – Dirk 2009-12-26 19:13:08