Array.shift() 從 JavaScript 數組中刪除第一項 [示例]
這個簡短的教程將向您展示如何使用 JavaScript Array.shift() 方法從數組中刪除項目,並提供一些代碼示例。
JavaScript 數組
一個數組 是一種變量類型,可以在其中保存零個或多個值。數組中的每個值都有一個位置,稱為 索引 – 這是一個整數值,表示項目在其出現順序中的位置。索引從位置 0 開始計數 – 所以數組中的第一項位於索引 0 ,索引 1 處的第二個項目 ,等等。
JavaScript 數組通常使用以下語法定義:
var myArray = [1, 2, 3]; // Define an array containing the numerical values 1, 2, 3
您可以在我們的文章中找到更多關於定義 JavaScript 數組的信息——在 JavaScript 中聲明數組的最佳方式。
使用 Array.shift() 方法從數組中刪除第一項
shift() 方法將從數組中刪除第一項(索引為 0 的項)並返回它。
JavaScript Array.shift() 語法
shift() 的語法 方法如下:
array.shift()
注意:
- 數組 可以是任何數組類型變量
- 可以為空
- shift() 將從調用它的數組中刪除元素
- shift() 將返回被移除元素的值
- 如果數組為空,則值為 undefined 將被退回
JavaScript Array.shift() 示例
以下代碼示例顯示了 shift() 方法與 JavaScript 數組一起使用:
var myArray = [1, 2, 3]; // Define an array containing the numerical values 1, 2, 3 console.log(myArray); // Print the array to the console for inspection var removedElement = myArray.shift(); // Call the shift() method on the array to remove the first element from the array and assign the value to the variable removedElement console.log(myArray); // The array will now have the value [2, 3] console.log(removedElement); // The variable removedElement will contain the value of the element removed from the array
下面的示例說明了當 shift() 時會發生什麼 在空數組上調用:
var myArray = []; // Define an empty array var removedElement = myArray.shift(); console.log(removedElement); // removedElement will have a value of undefined