Offer 驾到,掘友接招!我正在参与2022春招系列活动-刷题打卡任务,点击查看活动详情。
题目 range()
描述 请实现一个
range(from, to)
。
for (let num of range(1, 4)) {
console.log(num)
}
// 1
// 2
// 3
// 4
这个题目非常简单,注意你不一定必须要返回一个数组,你能想到除了for循环之外更多更炫酷的解法吗?
解题
-
最容易想到的,遍历返回一个数组
function range(from, to) { const res = []; while (from <= to) { res.push(from); from++; } return res; }
-
巧用类数组
function range(from, to) { return Array.from({ length: to - from + 1 }, (_, i) => i + from) }
-
generator 利用generator可以使用for of遍历的特性.
function range(from,to){ function *gen(){ while(from <= to) yield from++; } return gen() }