[Javascript] 提取 Array 內 Elements 的幾種簡單方法

Charlie H.
Aug 26, 2017 · 2 min read

相信大部分的初學者在剛開始接觸 JavaScript 的時候都遇過一樣的問題,我該怎麼樣處理那些我想使用的資料? 用簡單的 Object 包成一個 map 是滿不錯的選項,但我相信大部分剛開始起步的人直覺還是使用 Array 。 其實這問題的答案沒有對與錯,但我們要用的聰明點 😌。

我這篇文章想介紹的提取方法有許多人搞不清的四個:

push(), pop(), shift(), unshift()

I. push()

The push() method adds new items to the end of an array, and returns the new length.

意即新增一個element至array的最後面,並回傳新增後的長度

II. pop()

The pop() method removes the last element of an array, and returns that element.

意即從array的最尾端移出element,並回傳該element

III. shift()

The shift() method removes the first item of an array, and returns that item.

意即從array的最前端移出element,並回傳該element

IV. unshift()

The unshift() method adds new items to the beginning of an array, and returns the new length.

意即從array的最前端新增element,並回傳新增後的長度

結語

恭喜你,現在你已經會用四種方法去處理 Array 的頭跟尾的資料了。

參考:

  1. w3Schools.com
  2. the missing manual

)

Charlie H.

Written by

Hi, and goodbye.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade