如何创建可跳过空值的JavaScript自定义迭代器
JavaScript中的自定义迭代器解决方案
以下是实现SimpleClass的两种方案,均能通过重写Symbol.iterator跳过null或undefined类型的fields值:
方案一:使用生成器函数(推荐,写法简洁)
生成器函数是实现迭代器最直观的方式,代码可读性高:
class SimpleClass { constructor(items) { this.items = items; } *[Symbol.iterator]() { for (const item of this.items) { const fieldValue = item.fields; // 仅当字段值不是null或undefined时,返回该值 if (fieldValue !== null && fieldValue !== undefined) { yield fieldValue; } } } }
测试验证
使用你提供的测试代码验证:
const simple = new SimpleClass([ { fields: `a` }, { fields: `b` }, { fields: undefined }, { fields: null }, { fields: `e` }, ]); for (const val of simple) { console.log(val); // 依次输出: a b e }
方案二:手动实现迭代器协议
如果需要更精细地控制迭代流程,可以手动返回符合迭代器协议的对象:
class SimpleClass { constructor(items) { this.items = items; } [Symbol.iterator]() { let currentIndex = 0; const items = this.items; return { next() { // 循环遍历直到找到有效元素或遍历结束 while (currentIndex < items.length) { const fieldValue = items[currentIndex].fields; currentIndex++; if (fieldValue !== null && fieldValue !== undefined) { return { value: fieldValue, done: false }; } } // 遍历完成,返回结束标记 return { done: true }; } }; } }
原理说明
- 两种方案都通过重写对象的
Symbol.iterator属性,让SimpleClass实例成为可迭代对象,支持for...of循环等迭代操作。 - 核心逻辑都是遍历内部数组时,过滤掉
fields为null或undefined的元素,只返回有效数据。
内容的提问来源于stack exchange,提问作者gixlg
相关产品推荐
相关产品推荐

