js实现列表
使用数组创建列表
在JavaScript中,数组是最常用的列表实现方式。可以通过字面量或构造函数创建:
// 字面量方式
const list1 = [1, 2, 3, 'a', 'b'];
// 构造函数方式
const list2 = new Array(1, 2, 3);
数组提供多种操作方法:
push()添加元素到末尾pop()移除末尾元素shift()移除首元素unshift()添加元素到开头splice()在指定位置添加/删除元素
链表数据结构实现
对于需要频繁插入/删除的场景,可以手动实现链表:
class ListNode {
constructor(value) {
this.value = value;
this.next = null;
}
}
class LinkedList {
constructor() {
this.head = null;
this.size = 0;
}
add(value) {
const node = new ListNode(value);
if (!this.head) {
this.head = node;
} else {
let current = this.head;
while (current.next) {
current = current.next;
}
current.next = node;
}
this.size++;
}
}
使用Map/Set实现特殊列表
当需要唯一值或键值对结构时:
// Set实现值唯一的列表
const uniqueList = new Set();
uniqueList.add(1);
uniqueList.add(2);
uniqueList.add(1); // 不会被重复添加
// Map实现键值列表
const kvList = new Map();
kvList.set('key1', 'value1');
kvList.set('key2', 'value2');
使用生成器实现惰性列表
对于大数据量的懒加载场景:
function* generateList() {
let i = 0;
while (true) {
yield i++;
if (i > 10000) break;
}
}
const lazyList = generateList();
console.log(lazyList.next().value); // 0
console.log(lazyList.next().value); // 1
性能优化建议
- 大数据量查询优先考虑数组
- 频繁插入删除考虑链表结构
- 需要唯一性使用Set
- 现代JavaScript引擎对数组优化极好,多数场景应优先使用原生数组







