迭代器模式通过实现next()方法返回value和done属性,用于顺序访问集合元素。ES6引入Iterator接口,使数组、字符串等内置类型支持for...of循环和扩展运算符。Symbol.iterator方法让对象可迭代,自定义对象可通过添加该方法实现遍历。生成器函数function*简化迭代器创建,支持惰性求值与无限序列。常见遍历方式中,for...of基于迭代器协议,适合处理可迭代对象;while配合next()灵活但代码较长;forEach、map等适用于特定数据转换场景。掌握迭代器有助于理解JS遍历机制并编写通用逻辑。

JavaScript 中的迭代器模式是一种设计模式,用于顺序访问集合中的元素,而无需暴露其底层结构。这种模式在处理数组、类数组对象以及自定义数据结构时非常有用。ES6 引入了原生的 Iterator 接口,让很多内置类型默认可被遍历,并支持 for...of 循环和扩展运算符。
一个迭代器是一个对象,它定义了一个序列,并可能返回一系列值的终止状态。迭代器必须实现 next() 方法,该方法返回一个包含两个属性的对象:
当 done 为 true 时,表示迭代结束,此时 value 可选。
示例:手动创建一个简单的迭代器
立即学习“Java免费学习笔记(深入)”;
function createArrayIterator(arr) {
let index = 0;
return {
next: function() {
return index < arr.length ?
{ value: arr[index++], done: false } :
{ done: true };
}
};
}
<p>const iter = createArrayIterator([1, 2, 3]);
console.log(iter.next()); // { value: 1, done: false }
console.log(iter.next()); // { value: 2, done: false }
console.log(iter.next()); // { value: 3, done: false }
console.log(iter.next()); // { done: true }
为了让一个对象可被 for...of 遍历,它必须是“可迭代的”,即实现了 Symbol.iterator 方法。这个方法返回一个迭代器对象。
常见的可迭代对象包括:Array、String、Map、Set、arguments、NodeList 等。
示例:使用 Symbol.iterator 获取数组的迭代器
const arr = [10, 20];
const iterator = arr[Symbol.iterator]();
<p>console.log(iterator.next()); // { value: 10, done: false }
console.log(iterator.next()); // { value: 20, done: false }
console.log(iterator.next()); // { done: true }
你可以为自定义对象添加 Symbol.iterator 来使其可迭代。
const myCollection = {
items: ['a', 'b', 'c'],
[Symbol.iterator]() {
let index = 0;
return {
next: () => {
return index < this.items.length ?
{ value: this.items[index++], done: false } :
{ done: true };
}
};
}
};
<p>for (const item of myCollection) {
console.log(item); // 输出 a, b, c
}
不同的遍历方式适用于不同场景。以下是常见方法及其特点:
示例:for...of 遍历字符串和 Set
for (const char of "hi") {
console.log(char); // h, i
}
<p>for (const num of new Set([1, 2, 2])) {
console.log(num); // 1, 2
}
生成器函数(function*)是创建迭代器的简便方式。它会自动返回一个符合迭代器协议的对象。
function* gen() {
yield 1;
yield 2;
yield 3;
}
<p>const g = gen();
console.log(g.next()); // { value: 1, done: false }
console.log(g.next()); // { value: 2, done: false }
结合生成器可以轻松实现惰性求值、无限序列等高级功能。
function* idGenerator() {
let id = 1;
while (true) {
yield id++;
}
}
<p>const ids = idGenerator();
console.log(ids.next().value); // 1
console.log(ids.next().value); // 2
基本上就这些。掌握迭代器模式有助于理解现代 JavaScript 的遍历机制,也能写出更通用、可复用的数据处理逻辑。不复杂但容易忽略。
以上就是JavaScript迭代器模式_javascript遍历方法的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号