Haxe,如何检查param是否为Array类型

ren*_*846 5 arrays haxe

我正在将一个JavaScript库转换为Haxe.似乎Haxe与JS非常相似,但在工作中我遇到了覆盖函数的问题.

例如,在下面的函数param可以是整数或数组.

使用Javascript:

function testFn(param) {
    if (param.constructor.name == 'Array') {
        console.log('param is Array');
        // to do something for Array value
    } else if (typeof param === 'number') {
        console.log('param is Integer');
        // to do something for Integer value
    } else {
        console.log('unknown type');
    }
}
Run Code Online (Sandbox Code Playgroud)

HAXE:

function testFn(param: Dynamic) {
    if (Type.typeof(param) == 'Array') { // need the checking here
        trace('param is Array');
        // to do something for Array value
    } else if (Type.typeof(param) == TInt) {
        trace('param is Integer');
        // to do something for Integer value
    } else {
        console.log('unknown type');
    }
}
Run Code Online (Sandbox Code Playgroud)

当然HAXE支持Type.typeof(),但没有任何ValueTypeArray.我怎么解决这个问题?

Gam*_*a11 8

在Haxe中,您通常会使用Std.is()此代替Type.typeof():

if (Std.is(param, Array)) {
    trace('param is Array');
} else if (Std.is(param, Int)) {
    trace('param is Integer');
} else {
    trace('unknown type');
}
Run Code Online (Sandbox Code Playgroud)

它也可以使用Type.typeof(),但不太常见 - 您可以使用模式匹配来实现此目的.数组是ValueType.TClass,有一个c:Class<Dynamic>参数:

switch (Type.typeof(param)) {
    case TClass(Array):
        trace("param is Array");
    case TInt:
        trace("param is Int");
    case _:
        trace("unknown type");
}
Run Code Online (Sandbox Code Playgroud)