Did*_*exe 5 javascript iterator iterable linked-list ecmascript-6
我有一个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)
Run Code Online (Sandbox Code Playgroud)
问题是你current在检索之前要转移到下一个节点value.
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);
}Run Code Online (Sandbox Code Playgroud)
使用生成器函数实现迭代器要容易得多.
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);
}Run Code Online (Sandbox Code Playgroud)