1 回答
TA贡献1993条经验 获得超5个赞
旋转数组以将所需的数据放入currentItem
中间;那么你可以将中间之前的切片作为pastItems
,将中间元素作为currentItem
,将中间之后的切片作为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);
添加回答
举报