Haxe中的数组推导使用现有的语法使数组可以更简洁的初始化。它通过 for 或者 while循环构造:
Array comprehension in Haxe uses existing syntax to allow concise initialization of arrays. It is identified by for or while constructs:
class Main {
static public function main() {
var a = [for (i in 0...10) i];
trace(a); // [0,1,2,3,4,5,6,7,8,9]
var i = 0;
var b = [while(i < 10) i++];
trace(b); // [0,1,2,3,4,5,6,7,8,9]
}
}
变量 a 是被初始化为一个数组,保存从0到9的数值。编译器生成的代码,添加每次循环迭代的值到数组中,所以跟下面的代码是等价的:
Variable a is initialized to an array holding the numbers 0 to 9. The compiler generates code which adds the value of each loop iteration to the array, so the following code would be equivalent:
var a = [];
for (i in 0...10) a.push(i);
变量 b 是初始化为一个数组,保存同样的值,但是通过一个不同的推导样式,使用了 while 循环而不是 for 。再一次,跟如下的代码是等效的:
Variable b is initialized toan array with the same values, but through a different comprehension style using while instead of for. Again, the following code would be equivalent:
var i = 0;
var a = [];
while(i < 10) a.push(i++);
循环表达式可以是任何类型,包括条件和嵌套的循环,所以如下的内容会如预期运行:
The loop expression can be anything,including conditions and nested loops,so the following works as expected:
class Main {
static public function main() {
var a = [
for (a in 1...11)
for(b in 2...4)
if (a % b == 0)
a+ "/" +b
];
// [2/2,3/3,4/2,6/2,6/3,8/2,9/3,10/2]
trace(a);
}
}