如何在JavaScript中创建数组窗口化切片? [英] How to create windowed slice of array in javascript?

查看:173
本文介绍了如何在JavaScript中创建数组窗口化切片?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一个名为Array.window(n)的数组方法实现,该实现在具有参数n的数组上调用,将给出一个连续的重叠数组切片.

I'm looking for an array method implementation named Array.window(n) that invoked on an array with parameter n, would give a contiguous overlapping array slice.

示例:

let a = [1, 2, 3, 4, 5, 6]
a.window(2) // [[1, 2], [2, 3], [3, 4], [4, 5], [5, 6]]
a.window(3) // [[1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6]]
a.window(4) // [[1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6]]
a.window(10)// []

我该怎么做?

推荐答案

在这里,您将看到一个使用数组函数的简短示例:

Here you go with a slightly shorter example using array functions:

let a = [1, 2, 3, 4, 5, 6];
function windowedSlice(arr, size) {
    let result = [];
    arr.some((el, i) => {
        if (i + size >= arr.length) return true;
        result.push(arr.slice(i, i + size));
    });
    return result;
}
console.log(windowedSlice(a, 2));
console.log(windowedSlice(a, 3));
console.log(windowedSlice(a, 4));
console.log(windowedSlice(a, 5));

这篇关于如何在JavaScript中创建数组窗口化切片?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆