我有一个 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)
最佳答案
问题是您在检索 value
之前将 current
移动到下一个节点。
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) {
var value = current.value;
current = current.next;
return {value: value, done: false};
}
return {done: true};
}
};
};
for (const x of obj) {
console.log(x);
}
用 generator function 实现迭代器要容易得多.
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;
while (current) {
yield current.value;
current = current.next;
}
};
for (const x of obj) {
console.log(x);
}
关于javascript - 在 ES6 中使链表可迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42286657/