我有一个JavaScript中的链表,我需要使用for of
循环使其可迭代。我几乎做到了,但似乎没有办法将第一个值包含在结果中。这里是一个简化版本:
var obj = {value: 1, next: {value: 2, next: {value: 3, next: {value: 4, next: {value: 5, next: {value: 6, next: {value:7, next: null}}}}}}};
obj[Symbol.iterator] = function() {
var current = this;
return {
next() {
if (current.next !== null) {
current = current.next;
return {value: current.value, done: false};
}
return {done: true}
}
}
}
for (const x of obj) {
console.log(x)
}
// this is how you get the values printed with no loop
// console.log(obj.value + '->' + obj.next.value + '->' + obj.next.next.value)