js 实现list
使用数组(Array)实现列表
JavaScript 中数组是最常用的列表实现方式,支持动态增删元素和多种操作方法。
// 创建列表
const list = [1, 2, 3];
// 添加元素
list.push(4); // 末尾添加
list.unshift(0); // 开头添加
// 删除元素
list.pop(); // 删除末尾
list.shift(); // 删除开头
// 访问元素
console.log(list[1]); // 输出: 2
// 遍历列表
list.forEach(item => console.log(item));
使用链表(Linked List)实现列表
链表适合频繁插入/删除的场景,以下是单向链表的实现示例:
class ListNode {
constructor(value) {
this.value = value;
this.next = null;
}
}
class LinkedList {
constructor() {
this.head = null;
this.size = 0;
}
// 添加元素到末尾
append(value) {
const newNode = new ListNode(value);
if (!this.head) {
this.head = newNode;
} else {
let current = this.head;
while (current.next) {
current = current.next;
}
current.next = newNode;
}
this.size++;
}
// 删除指定值节点
remove(value) {
if (!this.head) return;
if (this.head.value === value) {
this.head = this.head.next;
this.size--;
return;
}
let current = this.head;
while (current.next) {
if (current.next.value === value) {
current.next = current.next.next;
this.size--;
return;
}
current = current.next;
}
}
}
使用 ES6 的 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* listGenerator() {
yield 1;
yield 2;
yield 3;
}
const genList = listGenerator();
for (const item of genList) {
console.log(item); // 依次输出1,2,3
}
使用 TypedArray 处理数值列表
处理二进制数据或类型化数组时:

// 创建包含10个元素的Int32数组
const typedList = new Int32Array(10);
typedList[0] = 42;
console.log(typedList.length); // 输出: 10






