在迴圈內依條件判斷新增元素


Posted by mijouhsieh on 2023-03-15

Document.createElement()

宣告新增元素的位置

Document.createElement()

const thumbsUpIcon = document.createElement('i')
thumbsUpIcon.classList.add('fa', 'fa-thumbs-up')

Q: 若要在score >=20 條件成立時加上icon,則icon應該要放在ABC的哪個位置?

debug-createElement In Code Position


位置A 宣告 新增的icon 放在 迴圈外層
debug-createElement In Code Position At A

因為從頭到尾只有產生一個讚的 icon,icon 會先放到流川楓名字旁,最後又被移動到三井壽名字旁。

位置B

每次 for 回圈都會宣告一個新的 thumbsUpIcon 變數,但如果分數不符合「得分數 ≥ 20」條件,這個變數就用不到。
=> 變成讓電腦花費時間和記憶體,去宣告一個不會用到的東西。

位置C

則能保證,電腦花費時間和記憶體宣告的 thumbsUpIcon 變數,一定會被使用到。


#debug-createElement







Related Posts

Git error -> fatal: the remote end hung up unexpectedly

Git error -> fatal: the remote end hung up unexpectedly

Day 01 典型統計應用在社群媒體分析(Classical statistics applied to social data) part 1

Day 01 典型統計應用在社群媒體分析(Classical statistics applied to social data) part 1

C# The way to store a temporary data: Memory Cache, Redis

C# The way to store a temporary data: Memory Cache, Redis


Comments