js 实现列表
使用数组创建列表
在JavaScript中,数组是最常用的列表实现方式。数组提供了一系列方法用于操作元素,如添加、删除、遍历等。
const list = [1, 2, 3, 4, 5];
list.push(6); // 添加元素到末尾
list.pop(); // 移除末尾元素
list.unshift(0); // 添加元素到开头
list.shift(); // 移除开头元素
使用链表实现列表
链表是一种动态数据结构,适合频繁插入和删除的场景。以下是单向链表的简单实现:

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实现特殊列表
对于需要唯一值或键值对的场景,可以使用ES6的Set或Map:
// 唯一值列表
const uniqueList = new Set();
uniqueList.add(1);
uniqueList.add(2);
uniqueList.add(1); // 重复值不会被添加
// 键值对列表
const keyValueList = new Map();
keyValueList.set('key1', 'value1');
keyValueList.set('key2', 'value2');
使用ArrayBuffer处理二进制列表
当需要处理二进制数据时,可以使用ArrayBuffer和类型数组:

const buffer = new ArrayBuffer(16); // 16字节的缓冲区
const int32View = new Int32Array(buffer); // 32位整数视图
int32View[0] = 42;
实现可迭代列表
通过实现迭代器协议,可以创建自定义可迭代列表:
class CustomList {
constructor() {
this.items = [];
}
[Symbol.iterator]() {
let index = 0;
return {
next: () => {
if (index < this.items.length) {
return { value: this.items[index++], done: false };
}
return { done: true };
}
};
}
}
使用生成器创建惰性列表
生成器可以用于创建按需计算的惰性列表:
function* generateSequence() {
yield 1;
yield 2;
yield 3;
}
const sequence = generateSequence();
for (let value of sequence) {
console.log(value);
}






