- Published on
แชร์ JavaScript Array Method ที่ใช้บ่อย ๆ ตอนที่ 4 : push, pop, shift, unshift
Overview
จากตอนที่สามเราได้รู้จักวิธีการใช้ indexOf
, lastIndexOf
, find
และ findIndex
กันไปแล้ว วันนี้จะแชร์ Array Method ที่เกี่ยวข้องกับการเพิ่มหรือลบข้อมูลใน array กันครับ ซึ่งจะมี push
, pop
, shift
, unshift
แล้วแต่ละตัวใช้ยังไงไปดูกันครับ
Array Data
ก่อนอื่นขอสมมติข้อมูล Array
ชื่อ cypto_currency
ที่เก็บชื่อของเหรียญเป็น string
ขึ้นมา
const cypto_currency = ['BTC','ETH','BNB','XRP','ADA','SOL']
push
push
เอาไว้เพิ่มข้อมูลใน array จากทางด้านหลัง
array.push(item)
ตัวอย่าง : อยากเพิ่มชื่อเหรียญ DOGE เข้าไปใน cypto_currency
ทางด้านหลัง
cypto_currency.push('DOGE')
console.log('cypto_currency', cypto_currency)
ผลลัพธ์
cypto_currency [
'BTC', 'ETH',
'BNB', 'XRP',
'ADA', 'SOL',
'DOGE'
]
pop
pop
เอาไว้ลบข้อมูลใน array ตัวสุดท้าย และสามารถเก็บข้อมูลไว้ในตัวแปรได้
array.pop()
ตัวอย่าง : อยากลบตัวสุดท้ายใน array และ เก็บค่าไว้ในตัวแปร last
const last = cypto_currency.pop()
console.log('last', last)
console.log('cypto_currency', cypto_currency)
ผลลัพธ์
last DOGE
cypto_currency [ 'BTC', 'ETH', 'BNB', 'XRP', 'ADA', 'SOL' ]
unshift
unshift
เอาไว้เพิ่มข้อมูลเหมือนกับ push
แต่เป็นการเพิ่มทางด้านหน้า
array.unshift(item)
ตัวอย่าง : อยากเพิ่มชื่อเหรียญ DOGE เข้าไปใน cypto_currency
ทางด้านหน้า
cypto_currency.unshift('DOGE')
console.log('cypto_currency', cypto_currency)
ผลลัพธ์
cypto_currency [
'DOGE', 'BTC',
'ETH', 'BNB',
'XRP', 'ADA',
'SOL'
]
shift
shift
คล้ายกับ pop
แต่เอาไว้ลบข้อมูลใน array ตัวหน้าสุด และสามารถเก็บข้อมูลไว้ในตัวแปรได้
array.shift()
ตัวอย่าง : อยากลบตัวสุดท้ายใน array และ เก็บค่าไว้ในตัวแปร last
const first = cypto_currency.shift()
console.log('first', first)
console.log('cypto_currency', cypto_currency)
ผลลัพธ์
first DOGE
cypto_currency [ 'BTC', 'ETH', 'BNB', 'XRP', 'ADA', 'SOL' ]
สรุปการใช้ push, pop, unshift, shift
push
ใช้เพิ่มข้อมูลใน array จากด้านหลังpop
ลบข้อมูล array ตัวสุดท้ายunshift
ใช้เพิ่มข้อมูลใน array จากด้านหน้าshift
ลบข้อมูล array ตัวหน้าสุด