2009-12-26 42 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