【问题标题】:Actionscript 3 array scope / multidimentional array questionsActionscript 3 数组范围/多维数组问题
【发布时间】:2009-12-26 18:57:59
【问题描述】:

我似乎遇到了数组范围问题。我有一个全局变量;

var itemConnect:Array = new Array();

在开始时初始化。然后我有一个函数可以将其填充为二维数组:

// 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()

我尝试在开始时将数组初始化为二维数组,如下所示:

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

似乎只能访问每个 [i] 节点中的一个,因此缺少 [1][2]、[1][3]、[1][4] - 只有最后一个 [j ] 元素出现。

这样做的正确方法是什么?我也不知道一开始数组的确切大小,这可能是个问题。

谢谢

【问题讨论】:

    标签: flash actionscript-3 multidimensional-array scope


    【解决方案1】:

    你的嵌套循环不是看起来更像这样吗?

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

    请注意,在这个版本中,内部数组的构造发生在循环之外,这意味着要对其进行迭代。

    【讨论】:

    • 是的;这绝对是一个问题。在您的代码中,您正在创建新的 [i] 数组 i*j 次——这不是您想要的。
    猜你喜欢
    • 2013-06-07
    • 1970-01-01
    • 1970-01-01
    • 2013-02-25
    • 2019-06-29
    • 1970-01-01
    • 2016-03-03
    • 1970-01-01
    • 2013-05-18
    相关资源
    最近更新 更多