DIV CSS 佈局教程網

JavaScript pop 方法移除數組末尾元素
編輯:JavaScript綜合知識     

pop() 與 push() 互為一對:前者從數組末尾取出並刪除一個元素,後者往末尾追加。兩者搭配使用,就把數組變成了一個標準的堆棧(後進先出)。

示例代碼

<!DOCTYPE html>
<html>
<body>
<p id="demo">Click the button to remove the last array element.</p>
<button onclick="myFunction()">Try it</button>

<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];

function myFunction() {
  fruits.pop();
  var x = document.getElementById("demo");
  x.innerHTML = fruits;
}
</script>
</body>
</html>

運行結果:

Banana,Orange,Apple

要點補充

pop() 返回的是被刪除的那個元素,而不是數組或長度,這與 push 恰好相反:

var arr = [1, 2, 3];
var last = arr.pop();    // last = 3
console.log(arr);        // [1, 2]

空數組調用 pop() 返回 undefined,不會報錯:

[].pop();    // undefined

如果只想刪除而不關心刪除了什麼,直接調用即可;若同時需要值和剩餘數據,用一行解构就能搞定:

var last = arr[arr.length - 1];
arr.length = arr.length - 1;    // 等價的傳統寫法

需要刪除頭部元素時用 shift(),需要一次刪除多個或指定位置的元素則用 splice()。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved