# 2620.Counter ###### tags:`Closure` | `leetCode` <font color="#01AE9A" background="E1F3F0">`easy`</font> ### 題目 Given an integer n, return a counter function. This counter function initially returns n and then returns 1 more than the previous value every subsequent time it is called (n, n + 1, n + 2, etc). ### Example ``` Input: n = 10 ["call","call","call"] Output: [10,11,12] Explanation: counter() = 10 // The first time counter() is called, it returns n. counter() = 11 // Returns 1 more than the previous time. counter() = 12 // Returns 1 more than the previous time. ``` ### Constraints: - `-1000 <= n <= 1000` - `At most 1000 calls to counter() will be made` --- ### 解題邏輯 這題是閉包的題目,關於閉包的概念大概就是==讓 function 內部具私有變數,而不被全域污染==,所以我想把 n+1存給n,再return n ```javascript= var createCounter = function(n) { return function() { n = n+1 return n-1 }; }; ``` 答案雖然有對但是總覺得 return n-1好像怪怪的,所以想了一下,結果有更簡潔的方式 ```javascript= var createCounter = function(n) { return function() { return n++ }; }; const counter = createCounter(10) counter()//10 counter()//11 counter()//12 ``` #### 容易搞混的遞增運算子 這邊要注意 n++ 使用了==遞增運算子==,放在 n 後面會先回傳 n 本身,再進行遞增,反之在前綴則會先進行遞增,再將遞增後的結果回傳。 ```javascript= let x = 3; y = x++; console.log("x",x)// 4 ->x被遞增1了 console.log("y",y)// 3 y是x沒被遞增的初始值 ``` ```javascript= let x = 3; y = ++x; console.log("x",x)// 4 ->x被遞增1後回傳 console.log("y",y)// 4 y是x被遞增後的值 ``` ### 參考連結 [PJ大大的閉包筆記-[JS] 深入淺出 JavaScript 閉包(closure)](https://pjchender.dev/javascript/js-closure/) <!-- {%hackmd @themes/orangeheart %} --> {%hackmd @themes/dracula %}
{"metaMigratedAt":"2023-06-18T03:33:21.766Z","metaMigratedFrom":"Content","title":"2620.Counter","breaks":true,"contributors":"[{\"id\":\"da4833e9-8c75-4c4a-9870-e972056b78eb\",\"add\":1738,\"del\":166}]"}
Expand menu