js列表实现增删查改
使用数组实现列表操作
JavaScript中数组(Array)是最常用的列表结构,以下是基于数组的增删查改实现方法:
初始化列表
let list = [1, 2, 3, 4]; // 基础初始化
let list2 = new Array(); // 空数组
增加元素
// 末尾添加
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(); // 返回5,列表变为[0,1,'new',2,3,4]
// 开头删除
list.shift(); // 返回0,列表变为[1,'new',2,3,4]
// 指定位置删除
list.splice(1, 1); // 删除index=1的元素,返回['new'],列表变为[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.splice(0, 2, 'a', 'b'); // 从0开始替换2个元素,列表变为['a','b',3,4]
使用链表实现列表操作
对于需要频繁插入删除的场景,可以自定义链表实现:
链表节点定义

class ListNode {
constructor(val) {
this.val = val;
this.next = null;
}
}
链表基本操作
class LinkedList {
constructor() {
this.head = null;
this.size = 0;
}
// 添加元素
add(val) {
const node = new ListNode(val);
if (!this.head) {
this.head = node;
} else {
let current = this.head;
while (current.next) {
current = current.next;
}
current.next = node;
}
this.size++;
}
// 删除元素
remove(val) {
if (!this.head) return false;
if (this.head.val === val) {
this.head = this.head.next;
this.size--;
return true;
}
let current = this.head;
while (current.next) {
if (current.next.val === val) {
current.next = current.next.next;
this.size--;
return true;
}
current = current.next;
}
return false;
}
// 查找元素
contains(val) {
let current = this.head;
while (current) {
if (current.val === val) return true;
current = current.next;
}
return false;
}
}
性能比较
数组适合随机访问和尾部操作,时间复杂度:
- 访问:O(1)
- 搜索:O(n)
- 插入/删除:头部O(n),尾部O(1)
链表适合频繁插入删除,时间复杂度:
- 访问:O(n)
- 搜索:O(n)
- 插入/删除:已知位置时O(1)
ES6+新特性
现代JavaScript提供了更简洁的操作方式:
// 扩展运算符添加元素
list = [...list, 6];
// 过滤删除
list = list.filter(x => x !== 3);
// 映射修改
list = list.map(x => x * 2);






