Jeff的隨手筆記

學習當一個前端工程師

0%

用LeetCode寫日記-Day29

今天的題目寫完感覺很簡單,但一開始在想覺得好難。
回去翻了很多之前的筆記><”

Day29: Array Wrapper

問題描述:

Create a class ArrayWrapper that accepts an array of integers in its constructor. This class should have two features:

  • When two instances of this class are added together with the + operator, the resulting value is the sum of all the elements in both arrays.
  • When the String() function is called on the instance, it will return a comma separated string surrounded by brackets. For example, [1,2,3].

問題難度:Easy

問題限制:

  • 0 <= nums.length <= 1000
  • 0 <= nums[i] <= 1000
  • Note: nums is the array passed to the constructor

我的學習過程:

這題感覺是要我們建立一個Function constructor,裡面有兩個method

因此我們先建立這個Function constructor:

1
2
3
4
5
6
var ArrayWrapper = function(nums) {
this.nums = nums
};

const obj1 = new ArrayWrapper([1,2])
console.log(obj1)

輸出會是:ArrayWrapper { nums: [ 1, 2 ] } 這表示我們這個Function constructor確實有建立好了

接下來就是分別建立兩個method,但我們不是直接建立在function裡面,而是使用Prototype的方式,至於為什麼我不能直接加在函式裡面就好,還要透過這個方式呢?

這就要牽扯到效能的問題了,我們當然可以把它直接放在函式裡,但不要忘了:Functions in JavaScript are objects

他們是會佔據記憶體空間的,因此如果我有1000個物件,就表示我會因為這個原因而需要1000個空間來放這個method,但如果我今天是使用是建立在 prototype 中,我們只需要一個空間來存放method。

現在回到題目:

我們先做簡單的加法,這邊有很多方法可以實現,這次一樣用reduce來實作:reduce(callbackFn, initialValue)

這個callbackFn 我們需要傳入兩個參數一個是初始值、一個是陣列的第一個元素

1
this.nums.reduce((accumulator, currentValue) => {accumulator, + currentValue}, 0)

接下來就是String() ,這邊有一個讓我比較想不透的就是如何實現**,** 這個真的是偷看答案才知道的原來這麼簡單,以下內容來自MND:

Array.prototype.join()

join() 方法會將陣列(或一個類陣列(array-like)物件 (en-US))中所有的元素連接、合併成一個字串,並回傳此字串。

1
2
3
4
const elements = ['Fire', 'Air', 'Water'];

console.log(elements.join());
// Expected output: "Fire,Air,Water"

因此我們只要先用.join()將數字陣列轉換成字串,在用[]包起來就可以了

1
`[${this.nums.join(',')}]`

到此所有實作都完成了

結論:

還剩下一天,明天寫完後就要開始整理這30天的文章內容,把它做成卡片筆記了