如何在 JavaScript 中移除陣列的最後一個元素並返回它?


在本教程中,我們將學習如何在 JavaScript 中移除陣列的最後一個元素並返回它。

在 JavaScript 中,陣列被描述為類似列表的物件。單個數組物件可以儲存多個值。陣列物件儲存在變數中。陣列元素儲存在記憶體位置中。每個陣列元素都由其索引值標識。

您必須透過插入元素、移除或更改等操作來處理陣列。JavaScript 有很多方法來更新陣列。讓我們看看在 JavaScript 中移除陣列最後一個元素的各種方法。

以下是移除最後一個數組元素的方法/函式:

  • Array pop() 方法

  • Array splice() 方法

使用 Array pop() 方法

Array 的 **pop()** 方法是用於移除陣列中最後一個元素的最簡單方法。pop() 方法會從原始陣列中返回移除的元素。

語法

下面給出的語法使用 pop() 方法移除陣列的最後一個元素。

arr.pop();

這裡 **arr** 是原始陣列。

示例

在下面給出的示例中,我們使用了 pop() 方法移除陣列的最後一個元素。我們使用了兩個陣列示例,並透過使用 pop() 移除每個陣列的最後一個元素。

<html> <head> </head> <body> <h3>Use <i>pop()</i> to remove the last element in an array</h3> <b>Example 1</b> <div id = "output1"></div> <b>Example 2</b> <div id = "output2"></div> <script> let output1 = document.getElementById("output1"); let output2 = document.getElementById("output2"); let output = ""; let arr1=[1,2,3,4,5]; output = "Array before pop(): "+arr1+"<br>"; output = output + "Removed element: "+arr1.pop()+"<br>"; output = output + "Array after pop(): "+arr1; output1.innerHTML = output; let arr2 = ["A","B","C","D","E", "F"]; output = "Array before pop() = "+arr2+"<br>"; output = output + "Removed element = "+arr2.pop()+"<br>"; output = output + "Array after pop() = "+arr2; output2.innerHTML = output; </script> </body> </html>

在以上兩個示例中,使用者可以看到 pop() 方法從陣列中返回了移除的元素,並更改了原始陣列。

使用 Array splice() 方法

splice() 方法用於向陣列新增或移除元素。

splice() 方法可以更改原始陣列。

語法

下面給出的語法使用 splice() 方法移除陣列的最後一個元素。

arr.splice(-1)
arr.splice(arr.length-1)

這裡 **arr** 是原始陣列。

示例

在下面給出的示例中,我們使用 splice() 方法移除陣列的最後一個元素。我們使用了兩個陣列示例,並透過使用 splice() 移除每個陣列的最後一個元素。

<html> <head> </head> <body> <h2>Use <i>splice()</i> method to remove the last element in an array</h2> <b>Example 1</b> <div id = "output1"></div> <b>Example 2 </b> <div id = "output2"></div> <script> let output1 = document.getElementById("output1"); let output2 = document.getElementById("output2"); let output = ""; let arr1 = [1,2,3,4,5]; output = "Array before splice() = "+ arr1 +"<br>"; output = output + "Output of the method = "+ arr1.splice(-1)+"<br>"; output = output + "The original array = "+arr1; output1.innerHTML = output; let arr2 = ["A","B","C","D","E"]; output = "Array before splice() = "+arr2+"<br>"; output = output+"Output of the method = "+arr2.splice(arr2.length-1)+"<br>"; output = output+"The original array = "+arr2; output2.innerHTML = output; </script> </body> </html>

我們學習了兩種方法,可以使用它們來移除 JavaScript 中的最後一個數組元素。在這些方法中,pop() 是移除陣列最後一個元素的最簡單方法。在實際問題中使用 pop() 方法是最佳實踐。

splice() 用於在特定索引上新增或移除元素。

更新於: 2022年8月26日

15K+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.