javascript - 如何使用 symbol.iterator 在 javascript 中使链表可迭代
问题描述
我正在尝试使我的单链表在 javascript 中可迭代,我尝试了注释的代码段,但一直未定义。我正在学习 javascript 链表和迭代,并尝试遍历列表并获取列表中每个数字的总和。我在这里检查并尝试了解决方案,但没有一个有效:(
// User defined class node
class Node {
// constructor
constructor(data)
{
this.data = data;
this.next = null
}
}
class LinkedList {
constructor(){
this.head = null;
this.size = 0;
}
add(data){
let node = new Node(data);
let current;
if(this.head === null){
this.head = node;
} else{
current = this.head;
while(current.next) {
current = current.next;
}
current.next = node;
}
this.size++
}
// [Symbol.iterator]() {
// let current = this.head;
// return {
// next: () => {
// if (!current) return { done: true };
// const { data, next } = current;
// current = next;
// return { data, done: false };
// },
// };
// }
log(){
let current = this.head;
let str = "";
while (current) {
str += current.data + ", ";
current = current.next;
}
if (str !== "") {
console.log(str);
} else{
console.log("List Is Empty");
}
}
}
let sum = 0;
for(const n of ll) {
console.log(n);
sum += n;
}
console.log(sum);
// "25"
ll.log();
解决方案
迭代器协议规定:
该
next()
方法必须始终返回具有适当属性的对象,包括done
和value
。
但是在您的代码中,返回的对象没有value
属性(而是data
属性)。这样做:
return { value: data, done: false };
Symbol.iterator
但是,将其定义为生成器似乎更自然:
* [Symbol.iterator]() {
let current = this.head;
while (current) {
yield current.data;
current = current.next;
}
}