LeetCode JavaScript 30 Days Challenge – Day23 – 2619. Array Prototype Last

    LeetCode JavaScript 30 Days Challenge

    Write code that enhances all arrays such that you can call the array.last() method on any array and it will return the last element.
    If there are no elements in the array, it should return -1.

    寫一個強調所有陣列的程式碼,這樣您可以在任何陣列中呼叫 array.last() 的方法,他會回傳最後一個元素。
    如果陣列中沒有元素,則應該回傳 -1。
    

    Example 1:

    Input: nums = [1,2,3]
    Output: 3
    

    Example 2:

    Input: nums = []
    Output: -1
    

    solution:
    依據題目需求建立一個 Array 的模型叫做 last,
    這一個函式可以在陣列呼叫時回傳最後一個元素,
    如果沒有元素則回傳 -1。

    Code 1: BigO(1)

    Array.prototype.last = function() {
      if (this.length) {
        return this[this.length - 1]
      }
      return -1;
    }
    

    FlowChart:
    Example 1

    nums = [1,2,3]
    console.log(nums.last()) //3
    

    Example 2

    nums = []
    console.log(nums.last()) //-1