gpt4 book ai didi

haxe - 在Haxe中将函数作为参数传递

转载 作者:行者123 更新时间:2023-12-03 23:23:25 28 4
gpt4 key购买 nike

在Haxe编程语言中,是否可以将函数作为参数传递(就像在JavaScript中一样?)

例如,以下代码在Haxe中是否有效?

function a(){
trace("This function is being used as a parameter!");
}

function b(theFunction){
theFunction();
}

b(a); //is this equivalent to a(); ?

最佳答案

这绝对是可能的,并且是标准库中使用的一种模式,尤其是在Lambda类中:

class Test {
static function main(){
var arr = [0,1,2,3,4,5,6,7,8,9,10];
var newArr = Lambda.filter(arr, function (num) {
return num % 2 == 0;
});
for (i in newArr)
{
trace (i);
}
}
}


(请参见 http://try.haxe.org/#C9dF3

要定义以函数作为参数的自己的方法,请使用 (param1Type)->(param2Type)->(returnType)语法:

function test1(myFn:String->Void) { myFn("hi"); }
test1(function (str) { trace(str); });

function test2(myFn:String->String) { var newStr = myFn("hi"); }
test2(function (str) { return str.toUpperCase(); });

function test3(myFn:Int->String->Array<Int>->Void) { myFn(3, "Jason", [1,2,3,4]); }
test3(function(num:Int, name:String, items:Array<Int>) { ... });

关于haxe - 在Haxe中将函数作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14025739/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com