陣列的 unshift() 方法可以在開頭加入一個或多個元素,並回傳插入後的新長度。它是 push() 的鏡像操作——一個加在尾端,一個加在頭部。
<!DOCTYPE html>
<html>
<body>
<p id="demo">Click the button to add elements to the array.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.unshift("Lemon", "Pineapple");
var x = document.getElementById("demo");
x.innerHTML = fruits;
}
</script>
<p><b>Note:</b> The unshift() method does not work properly in Internet Explorer 8 and earlier; the values will be inserted, but the return value will be <em>undefined</em>.</p>
</body>
</html>
執行後陣列變成:
Lemon,Pineapple,Banana,Orange,Apple,Mango
參數的順序會被保留:unshift("Lemon", "Pineapple") 的結果是 Lemon 在 Pineapple 前面,不是反過來。
相容性方面,IE8 及更早版本有個 bug:元素確實被插入了,但回傳值是 undefined 而非新長度。若你的程式依賴回傳值,在舊 IE 上就會出問題。
效能上要理解一件事:unshift 需要把既有元素全部往後挪一格,成本是 O(n)。若在迴圈中反覆對大陣列 unshift,效能會明顯惡化。這種情境下,先 push 到尾端、最後再一次 reverse(),通常快得多。