JS 筆記 splice()、slice()、split()

Same, Same But Different 易混淆部分

Jacy Chu
4 min readOct 16, 2021

整理 JavaScript Array 以及 String 切分

🚧 Leetcode 題目持續整理中 🚧

1. splice() 拼接 Array的就地刪除插入

Array.prototype.splice()

splice() 方法可以藉由刪除既有元素並/或加入新元素來改變一個陣列的內容。

array.splice(start[, deleteCount[, item1[, item2[, ...]]]])

e.g.

在 index 為 1 的位置,刪除 0 個字,再加上 Feb (會更動到原本的array)
const months = [‘Jan’, ‘March’, ‘April’, ‘June’];
months.splice(1, 0, ‘Feb’);
// inserts at index 1
console.log(months);
// expected output: Array [“Jan”, “Feb”, “March”, “April”, “June”]
在 index 為 4 的位置,刪除 1 個字,再加上 May (會更動到原本的array)
months.splice(4, 1, ‘May’);
// replaces 1 element at index 4
console.log(months);
// expected output: Array [“Jan”, “Feb”, “March”, “April”, “May”]

leetcode 題目

2. slice() 切割 Array的截取新片段

Array.prototype.slice()

slice() 方法會回傳一個新陣列物件(建議用一個新的變數接著),為原陣列選擇之 beginend(不含 end)部分的淺拷貝(shallow copy)。而原本的陣列將不會被修改。

arr.slice([begin[, end]])

e.g.

const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];從第二個位置開始擷取到最後(複製一份)
console.log(animals.slice(2));
// expected output: Array ["camel", "duck", "elephant"]
從第二個位置開始擷取到第四個位置(不包含第四)(複製一份)
console.log(animals.slice(2, 4));
// expected output: Array ["camel", "duck"]
擷取最後位置(複製一份)
console.log(animals.slice(-2));
// expected output: Array ["duck", "elephant"]
直接淺拷貝一份(複製一份)
console.log(animals.slice());
// expected output: Array ['ant', 'bison', 'camel', 'duck', 'elephant']

leetcode 題目

1752. Check if Array Is Sorted and Rotated (用到slice去拷貝一份)

3. split() String 的切割

String.prototype.split()

split()方法使用指定的分隔符字符串將一個String對象分割成子字符串數組,以一個指定的分割字串來決定每個拆分的位置。

str.split([separator[, limit]])

e.g.

const str = 'The quick brown fox jumps over the lazy dog.';以空格做切分
const words = str.split(' ');
console.log(words[3]);
// expected output: "fox"
淺拷貝一份
const strCopy = str.split();
console.log(strCopy);
// expected output: Array ["The quick brown fox jumps over the lazy dog."]

📐✏️ 📏

若有任何錯誤請在下方留言~🙏 Thanks!

--

--