js 实现list
在 JavaScript 中实现列表(List)功能可以通过数组(Array)或自定义数据结构完成。以下是几种常见方法:
使用内置数组
JavaScript 数组原生支持列表操作,包括增删改查和遍历:

const list = [1, 2, 3]; // 初始化
list.push(4); // 添加元素到末尾
list.unshift(0); // 添加元素到开头
list.pop(); // 移除末尾元素
list.shift(); // 移除开头元素
list.splice(1, 1); // 删除索引1的元素
自定义链表实现
对于需要频繁插入/删除的场景,可手动实现链表:

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++;
}
}
使用 ES6 类封装
通过类封装增强数组功能:
class CustomList {
constructor() {
this.items = [];
}
add(item) {
this.items.push(item);
}
remove(item) {
const index = this.items.indexOf(item);
if (index > -1) this.items.splice(index, 1);
}
get(index) {
return this.items[index];
}
}
不可变列表实现
使用扩展运算符实现不可变操作:
const original = [1, 2, 3];
const newList = [...original, 4]; // 添加元素
const filtered = original.filter(x => x !== 2); // 删除元素
性能注意事项
- 数组的
push/pop操作是 O(1),但shift/unshift是 O(n) - 链表插入/删除为 O(1),但随机访问需要 O(n)
- 大数据量时考虑使用 TypedArray 或链表结构






