I'm writing on Haxe and targeting Neko. Today I've encountered this problem:
我正在写Haxe并以Neko为目标。今天我遇到了这个问题:
var a:Array<Array<Int>> = new Array<Array<Int>>();
a[1] = [1, 2, 3];
The second line throws "Invalid array access" exception. Also it's impossible to iterate on row like this:
第二行抛出“无效的数组访问”异常。此外,不可能像这样迭代行:
for (i in a[0]) ...
A code like that always worked ok, but not the today one. What could be the problem here? The cells and rows I'm trying to access are guaranteed to exist (if talking about indexes).
像这样的代码总是正常,但不是今天的代码。这可能是什么问题?我试图访问的单元格和行保证存在(如果谈论索引)。
1 个解决方案
#1
8
This issue isn't Neko-specific: = new Array<Array<Int>>()
only initializes the outer array - it's equivalent to writing = []
. Since it's an empty array, any access will be out of bounds and return null
.
这个问题不是Neko特有的:= new Array
For your particular example, = [[], []]
would fix the error (initializes an array with two inner arrays). If you know the number of inner arrays you need beforehand, array comprehension is a convenient way to do the initialization:
对于您的特定示例,= [[],[]]将修复错误(使用两个内部数组初始化数组)。如果您事先知道需要的内部数组的数量,那么数组理解是一种方便的初始化方法:
var a:Array<Array<Int>> = [for (i in 0...numInnerArrays) []];
#1
8
This issue isn't Neko-specific: = new Array<Array<Int>>()
only initializes the outer array - it's equivalent to writing = []
. Since it's an empty array, any access will be out of bounds and return null
.
这个问题不是Neko特有的:= new Array
For your particular example, = [[], []]
would fix the error (initializes an array with two inner arrays). If you know the number of inner arrays you need beforehand, array comprehension is a convenient way to do the initialization:
对于您的特定示例,= [[],[]]将修复错误(使用两个内部数组初始化数组)。如果您事先知道需要的内部数组的数量,那么数组理解是一种方便的初始化方法:
var a:Array<Array<Int>> = [for (i in 0...numInnerArrays) []];