js列表实现增删查改
使用数组实现增删查改
JavaScript中数组(Array)是最常用的列表结构,以下是基于数组的增删查改操作示例:
初始化数组
let list = [1, 2, 3, 4];
增加元素
// 末尾添加
list.push(5); // [1, 2, 3, 4, 5]
// 开头添加
list.unshift(0); // [0, 1, 2, 3, 4, 5]
// 指定位置插入
list.splice(2, 0, 'new'); // [0, 1, 'new', 2, 3, 4, 5]
删除元素
// 末尾删除
list.pop(); // [0, 1, 'new', 2, 3, 4]
// 开头删除
list.shift(); // [1, 'new', 2, 3, 4]
// 指定位置删除
list.splice(1, 1); // [1, 2, 3, 4]
查询元素
// 按索引查询
let item = list[1]; // 2
// 按值查询索引
let index = list.indexOf(3); // 2
// 条件查询
let found = list.find(x => x > 2); // 3
修改元素
// 直接赋值修改
list[1] = 'updated'; // [1, 'updated', 3, 4]
// 批量修改
list = list.map(x => x * 2); // [2, 'updatedupdated', 6, 8]
使用链表实现增删查改
如需实现链表结构,需先定义节点类:
class ListNode {
constructor(val, next = null) {
this.val = val;
this.next = next;
}
}
初始化链表
let head = new ListNode(1, new ListNode(2, new ListNode(3)));
增加节点
// 头部插入
head = new ListNode(0, head);
// 尾部插入
let current = head;
while (current.next) current = current.next;
current.next = new ListNode(4);
// 指定位置插入
let pos = 1;
current = head;
for (let i = 0; i < pos - 1; i++) current = current.next;
current.next = new ListNode('new', current.next);
删除节点
// 头部删除
head = head.next;
// 尾部删除
current = head;
while (current.next.next) current = current.next;
current.next = null;
// 指定位置删除
pos = 2;
current = head;
for (let i = 0; i < pos - 1; i++) current = current.next;
current.next = current.next.next;
查询节点
// 按索引查询
pos = 1;
current = head;
for (let i = 0; i < pos; i++) current = current.next;
let nodeVal = current.val;
// 按值查询
current = head;
while (current && current.val !== 3) current = current.next;
let targetNode = current;
修改节点
// 直接修改值
pos = 1;
current = head;
for (let i = 0; i < pos; i++) current = current.next;
current.val = 'updated';
性能对比
- 数组:随机访问O(1),插入/删除头部O(n),插入/删除尾部O(1)/O(1)
- 链表:随机访问O(n),插入/删除头部O(1),插入/删除尾部O(n)
根据需求选择数据结构:

- 频繁随机访问 → 数组
- 频繁插入删除 → 链表






