如何在 JavaScript 陣列的末尾新增元素?


在本教程中,我們將學習如何向 JavaScript 陣列的末尾新增元素。向陣列末尾新增元素最常用的方法是使用 Array 的 push() 方法,但我們將討論多種可以實現此目的的方法。以下是實現此目的的一些方法。

  • 使用 Array.prototype.push( ) 方法

  • 使用 Array.prototype.splice( ) 方法

  • 使用陣列索引

使用 Array.prototype.push() 方法

要在末尾新增元素,請使用 JavaScript 的 push() 方法。JavaScript 陣列 push() 方法將給定元素追加到陣列的末尾,並返回新陣列的長度。

語法

以下是使用 push() 方法新增元素的語法:

arr.push(element)

這裡 arr 是要向其中新增元素的原始陣列。push() 方法返回陣列的長度。

示例

在這個例子中,我們建立一個名為 arr 的陣列,並向其中新增一些值。

<html> <head> <title>Program to add an element in the last of a JavaScript array</title> </head> <body> <h3>Adding an element in the last of the array using Array.push() Method</h3> </body> <script> // Create an array named arr let arr = [1, 2, 3, 4, 5]; // Add some value in the array arr.push(6); arr.push(7); arr.push(8); // Print the array document.write(arr) // 1,2,3,4,5,6,7,8 </script> </html>

使用 Array.prototype.splice 方法

JavaScript 陣列 splice() 方法更改陣列的內容,新增新元素並刪除舊元素。

語法

以下是使用 splice() 方法的語法:

array.splice(index, howMany, element1, ..., elementN);

引數

  • index − 這是開始更改陣列的索引。

  • howMany − 這是一個整數,表示要刪除的舊陣列元素的數量。如果為 0,則不刪除任何元素。

  • element1, ..., elementN − 要新增到陣列的元素。如果您沒有指定任何元素,splice 將只從陣列中刪除元素。

方法

要在陣列末尾新增值,我們將 splice 函式的第一個引數設定為陣列的長度減 1,第二個引數為 1,第三個引數為我們要追加的元素。如果要新增多個元素,需要將它們作為額外的引數傳遞到末尾。

示例

在這個例子中,我們建立一個名為 arr 的陣列,並向其中新增一些值。

<html> <head> <title>program to add an element in the last of a JavaScript array </title> </head> <body> <h3>Adding an element in the last of the array using Array.splice() Method</h3> </body> <script> // Create an array named arr let arr = [1, 2, 3, 4, 5]; // Add one element in the array arr.splice(arr.length, 1, 6) // Adding multiple elements at the end of the array arr.splice(arr.length, 3, "7th element", "8th element" , "9th element") // Print the array document.write(arr) // 1,2,3,4,5,6,7th element,8th element,9th element </script> </html>

使用陣列索引

眾所周知,JavaScript 中的陣列索引從 0 開始,到陣列元素數量減一結束。當我們在陣列末尾新增元素時,其索引將是陣列中的元素數量。為了將元素追加到陣列的末尾,我們將元素賦值到元素數量索引。

語法

Array.push( number of elements ) = element to be added

示例

在這個例子中,我們建立一個名為 arr 的陣列,並向其中新增一些值。

<html> <head> <title>program to add an element in the last of a JavaScript array </title> </head> <body> <h2>Adding an element in the last of the array using indexing </h2> </body> <script> // Create an array named arr let arr = [1, 2, 3, 4, 5]; // Add one element in the array arr[arr.length] = 6; arr[arr.length] = 7; arr[arr.length] = 8; // Print the array document.write(arr) // 1,2,3,4,5,6,7,8 </script> </html>

總之,在本教程中,我們討論了三種在 JavaScript 陣列末尾新增元素的方法。這三種方法是使用 Array 的 push() 和 splice() 方法,以及使用索引。

更新於:2022年8月22日

5K+ 瀏覽量

啟動您的 職業生涯

完成課程後獲得認證

開始學習
廣告
© . All rights reserved.