JavaScript 中的 Push() 對比 unshift()?
push() 對比 unshift()
push() 和 unshift() 方法用於向陣列中新增元素。但它們有細微差別。方法 push() 用於在陣列的末尾新增元素,而方法 unshift() 用於在陣列的開頭新增元素。讓我們詳細討論一下它們。
push()
語法
array.push("element");示例
在以下示例中,使用 push() 方法向一個 3 元素陣列的末尾新增另一個元素,並在輸出中顯示結果。
<html>
<body>
<script>
var companies = ["Spacex", "Hyperloop", "Solarcity"];
document.write("Before push:" +" "+ companies);
companies.push("Tesla");
document.write("</br>");
document.write("After push:" +" "+ companies);
</body>
</html>輸出
Before push: Spacex,Hyperloop,Solarcity After push: Spacex,Hyperloop,Solarcity,Tesla
unshift()
語法
array.unshift("element");示例
在以下示例中,使用 unshift() 方法向一個 3 元素陣列的開頭新增另一個元素,並在輸出中顯示結果。
<html>
<body>
<script>
var companies = ["Spacex", "Hyperloop", "Solarcity"];
document.write("Before unshift:" +" "+ companies);
companies.unshift("Tesla");
document.write("</br>");
document.write("After unshift:" +" "+ companies);
</script>
</body>
</html>輸出
Before unshift: Spacex,Hyperloop,Solarcity After unshift: Tesla,Spacex,Hyperloop,Solarcity
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP