Access last element of a TypeScript array

前端 未结 5 852
走了就别回头了
走了就别回头了 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 20:43

    If you don't need the array afterwards, you could use

    array.pop()
    

    But that removes the element from the array!

    The pop returns T | undefined so you need to take care of that in your implementation.

    If you are sure there will be always a value you can use non-null assertion operator (!):

         var poped = array.pop()
         array.push(poped!);
    

提交回复
热议问题