在JavaScript中在数组上滑动窗口 [英] Sliding window over Array in JavaScript

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

问题描述

我需要在JavaScript中的数组上滑动窗口.

I need a sliding window over an Array in JavaScript.

例如,在 [1,2,3,4,5,6,7,8,9] 上大小为 3 的滑动窗口应计算序列 [[1,2,3],[2,3,4],[3,4,5],[4,5,6],[5,6,7],[6,7,8],[7,8,9]] .

For example, a sliding window of size 3 over [1,2,3,4,5,6,7,8,9] shall compute the sequence [[1,2,3],[2,3,4],[3,4,5],[4,5,6],[5,6,7],[6,7,8],[7,8,9]].

以下是我的尝试,因为我找不到现成的解决方案:

The following is my attempt, because I couldn't find a readymade solution:

function window(a, sz) {
  return a.map((_, i, ary) => ary.slice(i, i + sz)).slice(0, -sz + 1);
}

它返回一个窗口数组,可以将其映射到以获取各个窗口.

It returns an array of windows that can be mapped over to get the individual windows.

什么是更好的解决方案?

What is a better solution?

推荐答案

通过原型添加到本机JavaScript对象不是一个好主意.这可能会以意想不到的方式破坏事物,并给您和其他使用您的代码的人带来很多挫败感.在这种情况下,最好只创建自己的函数.

Adding to the native JavaScript objects through their prototype is not a good idea. This can break things in unexpected ways and will cause a lot of frustration for you and anyone else using your code. It is better to just create your own function in this case.

要获得所需的功能,您可以简单地将数组传递给函数,然后从那里访问它.通过函数在数组上进行所需的方法调用.遵循KISS的原则,这里不再需要花哨的东西.

To get the functionality you want, you could simply pass the array to your function and then access it from there. Make the method calls you want on the array from your function. Following the principle of KISS, there's no need for anything more fancy here.

此外,请记住,将为数组的每个元素调用Array.map.这不是您真正需要的.如果目标是获得大小为n的滑动窗口,并且希望将每个窗口添加到新数组中,则可以使用如下函数:

Also, remember that Array.map is called for each element of the array. That's not really what you need here. If the goal is to get a sliding window of size n, and you want each of the windows to be added to a new array, you could use a function like this:

var myArray = [1, 2, 3, 4, 5, 6, 7, 8];

function getWindows(arr, n){
if (n > arr.length)
{
   return arr;
}
var result = [];
let lastWindow = i < arr.length/n - n;
for (let i = 0; i < lastWindow; i += n)
{
   result.push(arr.slice(i, i + n));
}

return result;

}

因此,在这里,我们将获得一个窗口数组,这些窗口也是数组.调用 console.log(getWindows(myArray,3)),给出以下输出:

So here, we will get an array of windows, which are also arrays. Calling console.log(getWindows(myArray, 3)), gives this output:

0:Array(3)[1,2,3]

0: Array(3) [ 1, 2, 3 ] ​

1:Array(3)[4,5,6]

1: Array(3) [ 4, 5, 6 ]

2:Array(3)[7,8,9]

2: Array(3) [ 7, 8, 9 ]

这篇关于在JavaScript中在数组上滑动窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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