JavaScript中用Iterator实现ES6规范的多维图形节点查找机制,核心是通过Symbol.iterator使自定义节点结构支持for...of等原生迭代,并借助NodeIterator类实现可配置的深度/广度优先遍历、过滤、链式查询及标准集合集成。

JavaScript 中用 Iterator 实现符合 ES6 规范的多维图形节点查找机制,核心是让自定义数据结构(如树、图、嵌套容器)支持 for...of、Array.from()、展开运算符([...iterable])等原生迭代能力,并能按需、可配置地遍历节点(比如深度优先、广度优先、按类型过滤、路径匹配等)。
1. 定义图形节点结构并实现 Symbol.iterator
先明确节点基本形态。假设每个图形节点是一个对象,含 type(如 "group"、"rect"、"path")、children(子节点数组,可能为空)、id、props 等字段:
class GraphicNode {
constructor(type, props = {}, children = []) {
this.type = type;
this.props = props;
this.children = Array.isArray(children) ? children : [];
this.id = props.id || Symbol();
}
<p>[Symbol.iterator]() {
// 默认按深度优先顺序遍历整个子树(含自身)
const stack = [this];
return {
next() {
if (stack.length === 0) return { done: true, value: undefined };
const node = stack.pop();
// 先压入子节点(逆序,保证左→右顺序)
for (let i = node.children.length - 1; i >= 0; i--) {
stack.push(node.children[i]);
}
return { done: false, value: node };
}
};
}
}2. 构建可配置的查找迭代器类(推荐方式)
直接在节点上写死一种遍历逻辑不够灵活。更实用的是封装一个独立的 NodeIterator 类,接收起始节点 + 配置项,返回标准迭代器:
class NodeIterator {
constructor(root, options = {}) {
this.root = root;
this.mode = options.mode || 'dfs'; // 'dfs', 'bfs', 'level-order'
this.filter = options.filter || (() => true);
this.maxDepth = options.maxDepth;
}
<p>*[Symbol.iterator]() {
if (!this.root) return;</p><pre class='brush:php;toolbar:false;'>if (this.mode === 'bfs') {
const queue = [{ node: this.root, depth: 0 }];
while (queue.length > 0) {
const { node, depth } = queue.shift();
if (this.maxDepth != null && depth > this.maxDepth) continue;
if (this.filter(node)) yield node;
if (node.children && depth !== this.maxDepth) {
for (const child of node.children) {
queue.push({ node: child, depth: depth + 1 });
}
}
}
} else {
// dfs:递归生成器(简洁可靠)
function* dfs(node, depth = 0) {
if (this.maxDepth != null && depth > this.maxDepth) return;
if (this.filter(node)) yield node;
if (node.children) {
for (const child of node.children) {
yield* dfs.call(this, child, depth + 1);
}
}
}
yield* dfs.call(this, this.root);
}} }
// 使用示例: const root = new GraphicNode('group', {}, [ new GraphicNode('rect', { id: 'r1' }), new GraphicNode('group', {}, [ new GraphicNode('path', { id: 'p1' }), new GraphicNode('circle', { id: 'c1' }) ]) ]);
// 查找所有 type === 'path' 的节点 const pathIterator = new NodeIterator(root, { filter: node => node.type === 'path' });
for (const node of pathIterator) { console.log(node.id); // 'p1' }
// 转成数组 const allRects = [...new NodeIterator(root, { filter: n => n.type === 'rect' })];
3. 支持链式查询与组合条件(增强实用性)
可扩展 NodeIterator 添加方法,返回新迭代器(不改变原状态),实现类似 jQuery 或 D3 的链式调用风格:
立即学习“Java免费学习笔记(深入)”;
class NodeIterator {
// ...constructor 和 [Symbol.iterator] 同上
<p>where(predicate) {
return new NodeIterator(this.root, {
...this.options,
filter: (node) => this.filter(node) && predicate(node)
});
}</p><p>findFirst() {
for (const node of this) return node;
return undefined;
}</p><p>byType(type) {
return this.where(node => node.type === type);
}</p><p>byId(id) {
return this.where(node => node.props.id === id);
}</p><p>limit(n) {
const iter = this[Symbol.iterator]();
return {
[Symbol.iterator]() {
let count = 0;
return {
next() {
if (count >= n) return { done: true };
const res = iter.next();
if (!res.done) count++;
return res;
}
};
}
};
}
}</p><p>// 链式用法:
const target = new NodeIterator(root)
.byType('group')
.where(n => n.children.length > 1)
.limit(1)
.findFirst();4. 与标准集合工具无缝集成
只要正确实现了 [Symbol.iterator],就能天然兼容 ES6+ 数组方法:
-
Array.from(iterator)→ 转为数组 -
[...iterator]→ 展开 -
Array.prototype.some / every / find / map→ 需先转数组,或配合生成器封装 -
for await...of不适用(除非是异步迭代器,此处为同步)
注意:若需支持 .map() 等高阶操作,建议导出为数组后处理,或封装 map(fn) 方法返回新迭代器(惰性)。
这套机制不侵入节点类本身,解耦清晰;支持多种遍历策略和动态过滤;完全符合 ES6 迭代协议,能直接用于现代 JS 生态链路。实际项目中还可结合 WeakMap 缓存路径、添加事件钩子(如 enter/leave)、支持反向遍历等,但基础骨架已足够健壮。


















