首頁 > web前端 > js教程 > 主體

Array.slice 與 Array.splice:消除混淆

PHPz
發布: 2024-08-09 14:33:07
原創
252 人瀏覽過

Array.slice vs. Array.splice: Clearing Up the Confusion

介紹

身為 JavaScript 開發人員,我經常發現兩個陣列方法有點難以掌握/完全

  1. 數組.slice
  2. 數組.splice。

因此,我決定深入研究並用清晰的範例來分解這些方法。

如果我重寫文法

Array.slice

returns the deleted elements in a form of Array = Array.prototype.slice(startIndex, endIndex-1);
登入後複製

Array.splice(P 代表永久 - 永遠記住)

JavaScript 中的 splice 方法透過刪除或取代現有元素和/或新增新元素來修改陣列的內容

刪除元素語法

returns the deleted elements in a form of Array = Array.prototype.splice(startIndex, endIndex-1); // permanent 

登入後複製

新增元素語法

array.splice(startIndex, 0, item1, item2, ..., itemX);
登入後複製

注意:-

  1. 它會改變原始陣列並傳回刪除的陣列。

  2. 當它表現為新增操作時,它會傳回 [],因為它沒有刪除任何內容。

讓我們來看一些例子:-

Q1。練習 1 - 使用切片取得陣列的一部分:建立一個包含從 1 到 10 的數字的陣列。使用切片方法取得包含從 4 到 8 的數字的新陣列。

const arr = Array.from(Array(10), (_, i) => i+1);
console.log('Array --> ', arr);
console.log('get a new array that includes numbers from 4 to 8 --> ', arr.slice(3, 8)); // Array.prototype.slice(startIndex, endIndex-1);

// [ 4, 5, 6, 7, 8 ]
登入後複製

Q2。練習 2 - 使用 splice 從陣列中刪除元素:建立一個水果陣列。使用 splice 方法從陣列中刪除「蘋果」和「香蕉」。

const fruits = ['apple', 'banana', 'orange', 'mango', 'kiwi'];

fruits.splice(0, 2)// permanent

console.log('splice method to remove "apple" and "banana" from the array. --> ', fruits);

// [ 'orange', 'mango', 'kiwi' ]
登入後複製

Q3。練習 3 - 使用 splice 將元素新增至陣列:建立顏色陣列。使用拼接的方法在「紅色」後面加上「粉紅色」和「紫色」。

const colors = ['red', 'green', 'blue'];

const y = colors.splice(1, 0, "pink", "purple"); /
console.log(y); // [] see above to see why.
console.log('splice method to add "pink" and "purple" after "red" --> ', colors)

// [ 'red', 'pink', 'purple', 'green', 'blue' ]
登入後複製

第四季。練習 4 - 使用切片和拼接:建立一個從「a」到「e」的字母陣列。使用 slice 取得前三個字母的新陣列。然後在原始數組上使用 splice 刪除這些字母。

const letters = ['a', 'b', 'c', 'd', 'e'];
const newSlice = letters.slice(0, 3);
const x = letters.splice(0, 3);
console.log(x);
console.log('slice to get a new array of the first three letters --> ', newSlice) // [ 'a', 'b', 'c' ]

console.log('Then use splice on the original array to remove these letters --> ', letters)[ 'd', 'e' ]
登入後複製

如果您有任何疑問/疑慮,請隨時與我聯絡。

以上是Array.slice 與 Array.splice:消除混淆的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!