如何通过轮播中的特定索引获取将来的项目和过去的项目 [英] How to get future items and past items by specific index like in a carousel

查看:103
本文介绍了如何通过轮播中的特定索引获取将来的项目和过去的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建自定义轮播.
而且我对算法一无所知.
我需要通过特定索引来获取将来和过去的项目.

I'm trying to create a custom carousel.
And I'm stuck with the algorithm.
I need to get future and past items by specific index.

旋转木马可以无限移动.

Carousel can move around infinitely.

示例:var exampleArray = [1,2,3,4,5,6,7,8,9];

Example: var exampleArray = [1,2,3,4,5,6,7,8,9];

slice(exampleArray,0);->>currentItem = [1],futureItems = [2,3,4,5],pasteItems = [6,7,8,9]
slice(exampleArray,4);->>currentItem = [5],futureItems = [6,7,8,9],pasteItems = [1,2,3,4]
slice(exampleArray,7);->>currentItem = [8],futureItems = [9,1,2,3],pastItems = [4,5,6,7]

slice(exampleArray, 0); -->> currentItem = [1], futureItems = [2,3,4,5], pastItems = [6,7,8,9]
slice(exampleArray, 4); -->> currentItem = [5], futureItems = [6,7,8,9], pastItems = [1,2,3,4]
slice(exampleArray, 7); -->> currentItem = [8], futureItems = [9,1,2,3], pastItems = [4,5,6,7]

推荐答案

您可以使用以下一种解决方案来

You can use one of the solutions to this question (I like @mickmackusa's) to rotate the array to get the desired currentItem into the middle; then you can just take the slice before the middle as pastItems, the middle element as currentItem, and the slice after the middle as futureItems:

const slicer = (arr, idx) => {
  let len = arr.length;
  let mid = Math.floor(len/2);
  let rotated = arr.slice(0);
  rotated = rotated.concat(rotated.splice(0, (mid + idx + 1) % len));
  return [rotated.slice(0, mid), [rotated[mid]], rotated.slice(mid+1)]
}

const exampleArray = [1,2,3,4,5,6,7,8,9];

[pastItems, currentItem, futureItems] = slicer(exampleArray, 0);
console.log(pastItems);
console.log(currentItem);
console.log(futureItems);

[pastItems, currentItem, futureItems] = slicer(exampleArray, 4);
console.log(pastItems);
console.log(currentItem);
console.log(futureItems);

[pastItems, currentItem, futureItems] = slicer(exampleArray, 7);
console.log(pastItems);
console.log(currentItem);
console.log(futureItems);

这篇关于如何通过轮播中的特定索引获取将来的项目和过去的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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