JavaScript中让自定义链表支持for-of循环,核心是实现符合规范的Iterator接口——即在链表类上部署[Symbol.iterator]()方法,返回一个具有next()方法的对象;该方法需惰性遍历、用闭包保存当前节点、每次返回{value, done}对象,从而支持for-of、扩展运算符等语法。

JavaScript中让自定义链表支持 for-of 循环,核心是实现符合规范的 Iterator 接口——即在链表类上部署 [Symbol.iterator]() 方法,返回一个具有 next() 方法的对象。
链表节点与链表类的基本结构
先定义清晰的节点和链表结构,便于后续迭代逻辑展开:
class ListNode {
constructor(value, next = null) {
this.value = value;
this.next = next;
}
}
class LinkedList {
constructor() {
this.head = null;
}
// 插入到头部(示例用法)
prepend(value) {
this.head = new ListNode(value, this.head);
}
}
为链表实现 Symbol.iterator 方法
这是关键一步:让 LinkedList 实例可被 for-of 消费。返回的迭代器需按需推进,每次调用 next() 返回 { value, done } 对象:
Java Maven 项目审查工作流的通用输入处理。当 Java Maven 项目以 ZIP压缩包或 GitLab 仓库 URL 形式提供且需要...时使用。
- 不要提前展开整个链表——避免创建中间数组,保持惰性求值和内存友好
- 用闭包保存当前遍历位置——避免修改链表内部状态(如临时指针),保证多次遍历互不影响
- done: true 时 value 可省略或设为 undefined,符合迭代器协议
class LinkedList {
// ... 其他方法
[Symbol.iterator]() {
let current = this.head;
return {
next() {
if (current === null) {
return { done: true };
}
const value = current.value;
current = current.next;
return { value, done: false };
}
};
}
}
用 for-of 直接遍历,简洁又语义清晰
实现后即可自然使用 for-of,无需手动管理指针,代码可读性强:
立即学习“Java免费学习笔记(深入)”;
const list = new LinkedList();
list.prepend(3);
list.prepend(2);
list.prepend(1);
for (const val of list) {
console.log(val); // 输出: 1 → 2 → 3
}
// 也支持解构、扩展运算符、数组方法等
const arr = [...list]; // [1, 2, 3]
const [a, b] = list; // a=1, b=2
进阶:支持反向遍历或带索引的迭代器
若需更多能力,可封装不同迭代器工厂方法,不破坏默认行为:
- 添加
entries()方法返回键值对迭代器:{ value: [index, value] } - 添加
reverse()方法返回从尾到头的迭代器(需先遍历一次收集节点,或改用双向链表) - 所有额外迭代器都应返回新对象,确保每次调用都是独立的遍历过程
// 示例:entries 迭代器
entries() {
let current = this.head;
let index = 0;
return {
next() {
if (current === null) return { done: true };
const pair = [index++, current.value];
current = current.next;
return { value: pair, done: false };
}
};
}
// 使用
for (const [i, val] of list.entries()) {
console.log(i, val); // 0 1 → 1 2 → 2 3
}

















