
您可以在 github 仓库中找到这篇文章中的所有代码。
/**
* @param {any} data
* @return {object}
*/
function createCustomIterable(data) {
return {
[Symbol.iterator]() {
let index = 0;
return {
next() {
if (index < data.length) {
return {
value: data[index++],
done: false,
};
} else {
return {
value: undefined,
done: true,
};
}
},
};
},
};
}
// Usage example:
const customIterable = createCustomIterable([1, 2, 3, 4]);
// Using for...of loop
for (const item of customIterable) {
console.log(item);
}
/**
* 1
* 2
* 3
* 4
*/
// Using spread operator
const arrayFromIterable = [...customIterable];
console.log(arrayFromIterable); // => [1, 2, 3, 4]
// Using Array.from()
const anotherArray = Array.from(customIterable);
console.log(anotherArray); // => [1, 2, 3, 4]
以上就是可迭代 - JavaScript 挑战的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号