Skip to content

Instantly share code, notes, and snippets.

@yangfch3
Last active October 15, 2016 05:58
Show Gist options
  • Save yangfch3/081f5ac8232f8ee25b8b7fe910ae8f7b to your computer and use it in GitHub Desktop.
Save yangfch3/081f5ac8232f8ee25b8b7fe910ae8f7b to your computer and use it in GitHub Desktop.
为对象添加遍历器以及使用遍历器实现指针结构(如链表)的遍历
/**
* 为 类或构造函数 的原型部署 Iterable 接口
* → 为 类或构造函数 的 prototype 对象部署 [Symbol.iterator] 方法
*/
function Obj(values) {
// values 为数组
this.values = values;
}
// 假设我们的遍历的目标是:遍历对象 values 数组的所有元素值
Obj.prototype[Symbol.iterator] = function() {
const self = this;
let index = 0;
return {
next() {
if(index < self.values.length) {
return {
value: self.values[index++],
done: false
};
}
return {
value: undefined,
done: true
};
}
}
}
let obj = new Obj([1,3,5,7]);
for (let i of obj) {
console.log(i);
}
/**
* 下面的遍历就不是指对单个对象的遍历了,而是对指针结构节点的遍历
* 这展示了:可以通过遍历器实现指针结构,如链表等
*/
function Obj(value) {
this.value = value;
// 指向指针结构的写一个节点
this.next = null;
}
Obj.prototype[Symbol.iterator] = function() {
var current = this;
function next() {
if (current) {
var value = current.value;
current = current.next;
return {
done: false,
value: value
};
} else {
return {
value: undefined,
done: true
};
}
}
var iterator = {
next: next
};
return iterator;
}
// 指针结构 one(next → two(next → three(next → null
var one = new Obj(1);
var two = new Obj(2);
var three = new Obj(3);
one.next = two;
two.next = three;
for (var i of one){
console.log(i);
}
// 1
// 2
// 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment