Access last element of a TypeScript array

前端 未结 5 837
走了就别回头了
走了就别回头了 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

    Here are a the options summarized together, for anyone finding this question late like me.

    var myArray = [1,2,3,4,5,6];
    
    // Fastest method, requires the array is in a variable
    myArray[myArray.length - 1];
    
    // Also very fast but it will remove the element from the array also, this may or may 
    // not matter in your case.
    myArray.pop();
    
    // Slowest but very readable and doesn't require a variable
    myArray.slice(-1)[0]
    

提交回复
热议问题