箭头函数中是否可以进行自递归?

时间:2016-11-04 22:34:25

标签: typescript

Vector3 velocity = Vector3.zero;

if (transform.rotation.x < -10)
{
    //do no forward or backward movement
    Debug.Log("Rotation too great to forward move...");
    tooGoodForMovement = true;
}
else
{
    tooGoodForMovement = false;
    if (Input.GetKey(KeyCode.W))
    {
        //Forward
        velocity = camera.forward * moveSpeed;
    }
    if (Input.GetKey(KeyCode.S))
    {
        //Back
        velocity = -camera.forward * moveSpeed;
    }
}
if (Input.GetKey(KeyCode.A))
{
    //Left
    velocity = -camera.right * moveSpeed;
}

if (Input.GetKey(KeyCode.D))
{
    //Right
    velocity = camera.right * moveSpeed;
}

velocity.Y = 0;
player.velocity = velocity;

我可以将此功能写为箭头功能吗?不确定javascript / typescript中是否支持这一点。

修改 我想在Array的filter方法中将此函数作为箭头函数传递。例如

   private recursiveFunction(node: any): boolean {
    var returnVal: boolean = false;
    if (node.name('ABC') !== -1) {
        return true;
    }
    if (node.children) {
        for (let child of node.children) {
            if (this.recursiveFunction(child)) {
                returnVal = true;
            }
        }
        return returnVal;
    }
}

2 个答案:

答案 0 :(得分:1)

是的,你可以

var recursiveFunction = (node: any): boolean => {
    var returnVal: boolean = false;
    if (node.name('ABC') !== -1) {
        return true;
    }
    if (node.children) {
        for (let child of node.children) {
            if (recursiveFunction(child)) {
                returnVal = true;
            }
        }
        return returnVal;
    }
}

答案 1 :(得分:1)

如果我理解你的意思那么:

let fn = (node: any) => {
    if (node.name('ABC') !== -1) {
        return true;
    }

    if (node.children) {
        return node.children.some(kid => fn(kid));
    }

    return node.hasValue();
};

let resultArray = someArray.filter(fn);

code in playground