自己实现一个 range 迭代器函数,模拟类似 python 的 for range 循环:
function* range(beg, end, step = 1) {
for (let i = 0; i < end; i += step)
yield i;
}
for (const i of range(0, 5))
console.log(i); // 0, 1, 2, 3, 4
for (const i of range(0, 10, 2))
console.log(i); // 0, 2, 4, 6, 8
虽然性能略差,但看起来是不是更简洁一些~
(之前发的贴沉了,所以重发一次)