เมธอด unshift เพิ่ม Element ที่ Index 0 และเลื่อนค่าที่ Index ต่อๆ ไปขึ้น แล้วคืนค่า Length ของ Array
เมธอด push() เพิ่ม Element ที่ท้าย Array และคืนค่า Element นั้น เมธอดนี้เปลี่ยน Length ของ Array
ตัวอย่าง
let fruits = ['apple', 'mango', 'orange', 'kiwi']; let fruits2 = ['apple', 'mango', 'orange', 'kiwi']; console.log(fruits.push("pinapple")) console.log(fruits2.unshift("pinapple")) console.log(fruits) console.log(fruits2)
ผลลัพธ์
5 5 [ 'apple', 'mango', 'orange', 'kiwi', 'pinapple' ] [ 'pinapple', 'apple', 'mango', 'orange', 'kiwi' ]
สังเกตว่าทั้งสอง Original Arrays ถูกเปลี่ยน
Unshift ช้ากว่า Push เพราะต้อง Unshift Elements ทั้งหมดไปซ้ายเมื่อเพิ่ม Element แรก