我正在尝试使用ES6类中的迭代器,并且在为我的类创建每个方法时遇到了引用错误:ReferenceError: vertex is not defined
。我能够将我的顶点添加到图形中,图形实例将打印出正确的数据。这个迭代器的使用是否正确?
class Vertex {
constructor(key) {
this.id = key
this.connectedTo = {}
}
}
class Graph {
constructor() {
this.vertexList = {}
this.numVerticies = 0
}
[Symbol.iterator]() {
// Reflect.ownKeys() === Object.keys()
const vertexListKeys = Reflect.ownKeys(this.vertexList)
let index = 0
return {
next: () => {
// Reflect.get(myObj, key) === Object[key]
let value = Reflect.get(this.vertexList, vertexListKeys[index])
index++
return {
done: index > vertexListKeys.length ? true : false,
value: value
}
}
}
}
// Iterate through vertexList values
each(callback) {
for (vertex of this) {
callback(vertex)
}
}
addVertex(key) {
const newVertex = new Vertex(key)
this.vertexList[key] = newVertex
this.numVerticies++
return newVertex
}
}
const graph = new Graph()
for (var i = 0; i < 6; i++) {
g.addVertex(i)
}
graph.each((vert) => console.log(vert))
// ReferenceError: vertex is not defined
// for (vertex of this) {
// ^
我也尝试将每个方法更改为生成器,但是当我这样做时,没有任何内容打印到控制台
*each(callback) {
for(vertex in this) {
yield callback(vertex) // omitting yield doesn't work either
}
}
答案 0 :(得分:2)
错误就是它所说的
for (vertex of this) {
使用未在任何地方声明的变量vertex
。它应该是
for (var vertex of this) {
或let
或const
。
答案 1 :(得分:0)
class Vertex {
constructor(key) {
this.id = key
this.connectedTo = {}
}
}
class Graph {
constructor() {
this.vertexList = {}
this.numVerticies = 0
}
[Symbol.iterator]() {
// Reflect.ownKeys() === Object.keys()
const vertexListKeys = Reflect.ownKeys(this.vertexList)
let index = 0
return {
next: () => {
// Reflect.get(myObj, key) === Object[key]
let value = Reflect.get(this.vertexList, vertexListKeys[index])
index++
return {
done: index > vertexListKeys.length ? true : false,
value: value
}
}
}
}
// Iterate through vertexList values
each(callback) {
for (var vertex of this) {
callback(vertex)
}
}
addVertex(key) {
const newVertex = new Vertex(key)
this.vertexList[key] = newVertex
this.numVerticies++
return newVertex
}
}
const g = new Graph()
for (var i = 0; i < 6; i++) {
g.addVertex(i)
}
g.each((vert) => console.log(vert))
在每个函数中,它应该是var vertex
,因为vertex
尚未声明。