# 数组的常用方法
# splice()
英/splaɪs/拼接
splice 在编程中意味着:
- 剪开:在指定位置"切断"数组
- 移除:拿走被剪掉的部分(可选)
- 连接:插入新元素,将数组重新"编织"在一起
实际应用示例
// 1. 只删除(像剪掉一段胶片)
const arr1 = [1, 2, 3, 4, 5];
arr1.splice(2, 2); // 从索引2开始删除2个元素
console.log(arr1); // [1, 2, 5]
// 2. 只插入(像在胶片中插入新画面)
const arr2 = [1, 2, 3];
arr2.splice(1, 0, 'a', 'b'); // 在索引1处插入,不删除
console.log(arr2); // [1, 'a', 'b', 2, 3]
// 3. 替换(像替换一段胶片)
const arr3 = [1, 2, 3, 4];
arr3.splice(1, 2, 'x', 'y', 'z'); // 删除2个,插入3个
console.log(arr3); // [1, 'x', 'y', 'z', 4]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
总结
splice 这个名字非常形象:
- 原意:将东西剪开并重新连接
- 编程中:在数组中剪开一个口子,移除和/或插入元素,然后重新连接
这种"外科手术式"的数组操作正是 splice 这个词的精髓所在!
# unshift()
意思:头部插入。
类比记忆
一个很好的类比是排队:
shift:就像队伍最前面的人离开了(被移除)。unshift:就像有人插队到了最前面,导致整个队伍向后移动了一步。
实例
let arr = [2, 3, 4];
// shift: 从开头移除一个元素
let firstElement = arr.shift();
console.log(firstElement); // 输出:2
console.log(arr); // 输出:[3, 4]
// unshift: 在开头添加元素(与shift操作方向相反)
arr.unshift(1);
console.log(arr); // 输出:[1, 3, 4]
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
总结
unshift 这个名字来源于其行为是 shift 的“反向操作”:
shift:移除数组头部的元素。unshift:在数组头部添加元素。
# splice()参数说明
interface Array<T> {
splice(start: number, deleteCount?: number): T[];
splice(start: number, deleteCount: number, ...items: T[]): T[];
}
1
2
3
4
5
6
7
2
3
4
5
6
7
splice() 函数有多个参数,但它的参数结构很灵活。具体来说:
参数结构
array.splice(start, deleteCount, item1, item2, ..., itemN)
1
参数详解
start(必需)- 开始修改的索引位置
deleteCount(可选)- 要删除的元素个数
- 如果省略或值大于数组长度,则删除从 start 之后的所有元素
item1, item2, ..., itemN(可选)- 要添加到数组的元素
- 从
start位置开始插入
你的示例分析
// 1. 2个参数:start=2, deleteCount=2
arr1.splice(2, 2);
// 2. 4个参数:start=1, deleteCount=0, item1='a', item2='b'
arr2.splice(1, 0, 'a', 'b');
// 3. 5个参数:start=1, deleteCount=2, item1='x', item2='y', item3='z'
arr3.splice(1, 2, 'x', 'y', 'z');
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
总结
- 最少参数:1个(
start) - 最多参数:理论上无限个,但至少需要1个参数
- 核心特点:参数数量可变,功能非常灵活
这就是为什么 splice 被称为数组的"瑞士军刀"——一个方法就能实现删除、插入、替换等多种操作!