Jeff的隨手筆記

學習當一個前端工程師

0%

用LeetCode寫日記-Day22

好久沒來咖啡廳唸書了,今天目標在咖啡廳把每日目標都完成!

Day22: Array Prototype Last

問題描述:

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.

You may assume the array is the output of JSON.parse.

問題難度:Easy

問題限制:

  • arr is a valid JSON array
  • 0 <= arr.length <= 1000

我的解題過程:

只要懂的this,這就是一題很簡單的問題。題目的要求是把傳入的array的最後一個元素回傳,如果是空的array則是回傳-1。

因此簡單的判斷式:

1
if (this.length === 0) {code} else {code}

裡面的this是指向呼叫這個function 的array,當array的長度是0時就執行題目的要求,不為0時(長度不會有負數)就執行回傳最後一個元素。

因為array的計算是從0開始,因此我們必須要讓this.length -1 才能會是我們要的最後一個元素,也就是**this[this.length -1]**

我的code:

1
2
3
4
5
6
7
Array.prototype.last = function() {
if (this.length === 0) {
return -1
} else {
return (this[this.length -1])
}
};

其他解法:

1
2
3
Array.prototype.last = function() {
return this.length ? this[this.length - 1] : -1;
};

因為0會判斷成false,因此我們可以使用三元運算

總結:

30天要結束了,發現慢慢的很多東西都是開始重複了,已經不像第一次看到這個類型的題目會搞不清楚狀況,看來我好像有點進步…還是這是我的錯覺只是這題特別簡單XDD