如何使用 symbol.iterator 使链表在 javascript 中可迭代

How do I make a linked list iterable in javascript using symbol.iterator

我正在尝试使我的单链表在 javascript 中可迭代,我尝试了注释代码,但一直未定义。 我正在学习 javascript 链表和迭代,并尝试遍历列表并获取列表中每个数字的总和。 我在这里查看并尝试了解决方案,但其中 none 有效:(

// 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();

iterator protocol规定:

The next() method must always return an object with appropriate properties including done and value.

但是在您的代码中,返回的对象没有 value 属性(而是 data 属性)。也一样:

return { value: data, done: false };

不过,将Symbol.iterator定义为生成器似乎更自然:

* [Symbol.iterator]() {
    let current = this.head;
    while (current) {
        yield current.data;
        current = current.next;
    }
}