这个问题已经被很多语言问过,但还没有被JavaScript问过。
Ruby有一个名为Enumerable#each_cons
的方法,看起来像这样:
puts (0..5).each_cons(2).to_a
# [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5]]
puts (0..5).each_cons(3).to_a
# [[1, 2, 3], [2, 3, 4], [3, 4, 5]]
在JavaScript中,我如何使用Array
来实现类似的方法?
Array.from({length:array.length - num + 1}, (_, i) => array.slice(i, i + num))
。 - charlietflmap
并使用内部映射器本身。与你现在混合在一起的解决方案相比,这肯定会有性能提升。 - claasic