JavaScript >> Javascript 文檔 >  >> JavaScript

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


Tutorial JavaScript 教程
  1. 如何使用 FormData 和 React Hook 表單進行多部分文件上傳

  2. JavaScript 數據結構:哈希表:簡介

  3. 發現你如何學習最好,越早越好。

  4. 一個有爭議的雙重平等案例

  5. ERROR 錯誤:沒有 ToastsManager 的提供者

  6. Angular JS 與 React JS

  7. 提交後清除我的表單輸入

  1. 如何在javascript中計算字符串的行數

  2. 在 Angular 中處理多個項目

  3. Flutter Wave 支付集成

  4. 如何在管道地圖中處理承諾

  5. 讓我們看中控制台簽名

  6. 代碼和 Scrum 100 天中的第 65 天:平凡的重構和代碼清理

  7. 如果用戶更改了 CSS 樣式,則觸發事件?

  1. 如何使用 JavaScript 獲取文件擴展名?

  2. 精益 Angular 組件

  3. 對 Hey.com 技術的一些偷窺(V - 刺激增強)

  4. 使用 VueJS、Vuetify 和 SortableJS 的可拖動表格行