面试题答案
一键面试// 创建迭代器函数
function createArrayIterator<T>(array: T[]): Iterator<T> {
let index = 0;
return {
next(): IteratorResult<T> {
if (index < array.length) {
return { value: array[index++], done: false };
} else {
return { value: undefined, done: true };
}
}
};
}
// 使用示例
const myArray = [1, 2, 3, 4, 5];
const iterator = createArrayIterator(myArray);
let result = iterator.next();
while (!result.done) {
console.log(result.value);
result = iterator.next();
}