# DAY25 - JavaScript 39. 陣列新增資料的兩個方法,push、unshift ### .push() - 在原有的陣列資料中,從最後一筆來新增資料。 ``` // 陣列資料: let colors = ["red", "green", "blue"]; // 新增資料: colors.push("pink"); console.log(colors); console.log(colors[3]); 成功新增資料: // (4) ['red', 'green', 'blue', 'pink'] // pink ``` - **push** 的新增方式,較為直覺,也是常見可以理解的做法。 ### .unshift() - **unshift**與 push 的不同: unshift,是從原有的陣列中,**從最前面** 來新增資料,與 push 的從最後面直接新增 有些不同 ``` // 陣列資料: let colors = ["red", "green", "blue"]; // 新增資料: colors.unshift("pink"); console.log(colors); console.log(colors[0]); 成功新增資料: // (4) ['pink', 'red', 'green', 'blue'] // pink ``` ### .unshift() 的應用 - 類似留言板系統,大多數人在新增留言時,應該都會希望 最新的留言內容,顯示在最新或是最上面的吧。 ###### tags: `Re:0 前端工程師之路 - JavaScript - 陣列與物件 篇章`
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up