简体   繁体   English

Haxe 获取数组最后一个元素

[英]Haxe get array last element

In haxe is there some way to get the last element of an array other than using arr[arr.length-1] as key?在 haxe 中,除了使用arr[arr.length-1]作为键之外,还有其他方法可以获取数组的最后一个元素吗? I would like to avoid needing a reference to the array.我想避免需要对数组的引用。

No, but you could create a static extension for it:不,但您可以为其创建一个static 扩展

using ArrayExtensions;

class Main {
    static function main() {
        var a = [1, 2, 3];
        trace(a.last()); // 3
    }
}
class ArrayExtensions {
    public static inline function last<T>(a:Array<T>):T {
        return a[a.length - 1];
    }
}

Alternatively, you could overload the array access operator with a custom abstract to get Python-style negative indices:或者,您可以使用自定义抽象重载数组访问运算符以获取 Python 样式的负索引:

class Main {
    static function main() {
        var a:PythonArray<Int> = [1, 2, 3];
        trace(a[-1]); // 3
    }
}

@:forward
abstract PythonArray<T>(Array<T>) from Array<T> to Array<T> {
    @:arrayAccess function get(i) {
        return if (i < 0) this[this.length - i * -1] else this[i];
    }

    @:arrayAccess function set(i, v) {
        return if (i < 0) this[this.length - i * -1] = v else this[i] = v;
    }
}

This has the downside that the array has to be typed as that abstract.这样做的缺点是必须将数组键入为该抽象。

Two obscure ways to achive similar, Gama11 solutions seem better, but always check speeds on targets if it's important, I have used null on js test, but often better to set to a valid value, some targets you may need Null or similar.实现相似的两种模糊方法,Gama11 解决方案似乎更好,但如果重要,请始终检查目标的速度,我在 js 测试中使用了 null,但通常最好设置为有效值,某些目标可能需要 Null 或类似的。

using Test;
class Test {
    static function main() {
        var arr = [0,1,2,3];
        trace( arr.last() );
    }
    static inline function last<T>( arr: Array<T>, j=null ){
        for( i in arr ) j = i;
        return j;
    }
}

This seems to create more verbose code.这似乎会创建更冗长的代码。

class Test {
    static function main() {
        var arr = [0,1,2,3];
        var j = null;
        arr.map((i)->j=i);
        trace(j);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM