js实现list
在 JavaScript 中实现列表(List)
JavaScript 中没有内置的 List 数据结构,但可以通过数组(Array)或自定义类实现类似功能。以下是几种常见方法:
使用数组(Array)
数组是 JavaScript 中最接近 List 的数据结构,提供多种操作方法:

// 创建列表
const list = [1, 2, 3];
// 添加元素
list.push(4); // 末尾添加
list.unshift(0); // 开头添加
// 删除元素
list.pop(); // 移除末尾元素
list.shift(); // 移除开头元素
// 访问元素
console.log(list[0]); // 访问第一个元素
// 遍历列表
list.forEach(item => console.log(item));
自定义 List 类
如果需要更严格的 List 实现,可以创建自定义类:

class List {
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);
}
}
size() {
return this.items.length;
}
isEmpty() {
return this.size() === 0;
}
}
// 使用示例
const myList = new List();
myList.add('a');
myList.add('b');
console.log(myList.size()); // 2
使用链表实现
对于需要频繁插入/删除的场景,链表可能更高效:
class ListNode {
constructor(value) {
this.value = value;
this.next = null;
}
}
class LinkedList {
constructor() {
this.head = null;
this.tail = null;
this.length = 0;
}
append(value) {
const newNode = new ListNode(value);
if (!this.head) {
this.head = newNode;
this.tail = newNode;
} else {
this.tail.next = newNode;
this.tail = newNode;
}
this.length++;
}
}
使用第三方库
对于复杂需求,可以考虑使用第三方库如:
- Immutable.js(不可变列表)
- lodash(提供更多数组操作方法)
性能考虑
- 数组适合随机访问,但中间插入/删除较慢
- 链表适合频繁插入/删除,但随机访问需要遍历
- 大数据量考虑使用 TypedArray 提高性能






