隨手記-以前看不懂但現在看懂了


Posted by Rich on 2021-08-23

最近寫 React,感覺新手時期很多看不懂的東西,有越來越懂的感覺。但到底差在哪?

todos.filter((todo) => {
        if (todo.id !== id) return true;
        return false;
      })

這東西我一個月前應該是看不懂的,雖然主要原因是我不知道 filter 在幹嘛。
filter 只是單純將 todos 裡面的東西,符合條件的留下來。怎麼留下來? return true 就留下來。return false 就刪掉。
所以這句就是 todo 的 id 不等於 id 就留下來。一樣就刪掉。
但這也可以這樣寫。

todos.filter((todo) => {
        return (todo.id !== id) 
      })

因為 todo.id !== id 就會判斷出 true or false。就像你在瀏覽器的 console 隨便亂打,123 === 321 他就會跑出 false 一樣。
還可以在簡寫

todos.filter((todo) =>  (todo.id !== id))

當只有整個函式只有 return 的時候,可以將{}return 一起省略,就變成上面那樣。
我以前真的是看不懂啊。


#notes







Related Posts

6. 排序 (上篇)

6. 排序 (上篇)

Linkedin  Java 檢定題庫 static import

Linkedin Java 檢定題庫 static import

[Note] React Leaflet

[Note] React Leaflet


Comments