【JavaScript】循环获取数组中固定个数元素

最近在做循环列表的过程中,由于无法简单使用ElementUI现成的Siwper实现一次4个元素的循环显示。

于是,自己动手,丰衣足食:

  • 直接使用for循环根据点击实现循环显示想要的4个元素;
  • 根据click时间,决定获取获取元素。

然后犯懒,去百度了一把看有没有现场的函数可以用,无奈没有好用的。分享一下自己的,并留作备用吧。

效果验证:

  let textAllData = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  let index = 0

下面是打印值:

[ 1, 2, 3, 4 ]
[ 2, 3, 4, 5 ]
[ 3, 4, 5, 6 ]
[ 4, 5, 6, 7 ]
[ 5, 6, 7, 8 ]
[ 6, 7, 8, 9 ]
[ 7, 8, 9, 10 ]
[ 8, 9, 10, 1 ]
[ 9, 10, 1, 2 ]
[ 10, 1, 2, 3 ]
[ 1, 2, 3, 4 ]
[ 2, 3, 4, 5 ]
/**
* @allData: 待处理数组
* @n: 返回元素个数
* @index:
*/
prev4Items(allData, n, index) {
    
    
  let startIndex = index;
  let length = allData.length
  let newArr = []
  if(startIndex < 0){
    
    
    newArr = [...allData.slice(length + startIndex, length), ...allData.slice(0, n + startIndex)]
    startIndex = length + startIndex - 1
  }else if (startIndex >= 0 && startIndex <= length - n){
    
    
    newArr = allData.slice(startIndex, startIndex + n)
    startIndex -= 1
  }else if(startIndex > length - n){
    
    
    newArr = [...allData.slice(startIndex, length), ...allData.slice(0, n - (length-startIndex))]
    startIndex -=1
  }
    return [newArr, startIndex]
},
    
next4Items(allData, n,index) {
    
    
  let startIndex = index;
  let length = allData.length;
  let newArr = [];
  
  if(index <= length - n){
    
    
    newArr = allData.slice(startIndex, startIndex + n)
    startIndex += 1
  }else if (length - n< startIndex && startIndex< length ){
    
    
    newArr = [...allData.slice(startIndex, length), ...allData.slice(0, n -(length-startIndex))]
    startIndex += 1
  }else{
    
    
    startIndex = 0
    newArr = allData.slice(startIndex, startIndex + n)
    startIndex += 1
  }
  return [newArr,startIndex]
},

Guess you like

Origin blog.csdn.net/qq_38987146/article/details/117121477