Access last element of a TypeScript array

前端 未结 5 835
走了就别回头了
走了就别回头了 2021-02-06 20:23

Is there a notation to access the last element of an array in TypeScript? In Ruby I can say: array[-1]. Is there something similar?

5条回答
  •  暖寄归人
    2021-02-06 21:06

    If you need this call more often it's possible to declare it globally:

    interface Array {
        last(): T | undefined;
    }
    if (!Array.prototype.last) {
        Array.prototype.last = function () {
            if (!this.length) {
                return undefined;
            }
            return this[this.length - 1];
        };
    }
    

    then you can just call

    items.last()
    

提交回复
热议问题