以下需求怎么用简单的代码实现

假设有50条数据,默认一出来就展示3条 然后点击换一批 换成其他三条 在点击一批 又换成其他三条 每次都是出来三条 且跟之前的不重复 然后50条数据继续这样执行

阅读 2k
4 个回答

可以滚动取值,取值的数据然后在插入到数据的末端,大致如下:

let newInfoList = [1,2,3,4,5,6,7,8,9,10,11];

function getInfo() {
    const backNewInfo = newInfoList.splice(0,3)
    newInfoList = newInfoList.concat(backNewInfo)
    return backNewInfo
}

按顺序,不随机取:

let candidate = Array.from({ length: 50 }, (_, i) => i)
let display = []

function refresh() {
  if (candidate.length < 3) {
    // 重新取数据
    candidate = Array.from({ length: 50 }, (_, i) => i)
  }

  display = candidate.splice(0, 3)
}

// 初始化执行一次
refresh()

随机取:

let candidate = Array.from({ length: 50 }, (_, i) => i)
let display = []

function refresh() {
  if (candidate.length < 3) {
    // 重新取数据
    candidate = Array.from({ length: 50 }, (_, i) => i)
  }

  // 0 ~ candidate.length - 3 区间取随机位置,截取 3 个数据
  display = candidate.splice(Math.round(Math.random() * (candidate.length - 3)), 3)

  // 也可以随机取一个数据,重复执行 3 次
  display = Array.from(
    { length: 3 },
    () => candidate.splice(Math.round(Math.random() * (candidate.length - 1)), 1)[0]
  )
}

// 初始化执行一次
refresh()

如果并不需要重新取数据,只需要把源数据浅拷贝一份出来即可:

// 源数据
const source = Array.from({ length: 50 }, (_, i) => i)
// 浅拷贝
let candidate = Array.from(source)
class NextAble {
  current = 0
  size = 3
  list = []

  constructor(list) {
    this.list = list
  }

  get displayList() {
    const {current, size} = this
    return this.list.slice(current * size, (current + 1) * size)
  }
  get canNext() {
    return this.list[(this.current+1) * this.size] !== undefined
  }


  next() {
    if (!this.canNext) {
      this.current = 0
      return
    }
    this.current += 1
  }
}

const list = Array(29).fill(0).map((n,i) => i)
const ins = new NextAble(list)

setInterval(() => {
  console.log(ins.current, ins.displayList)
  ins.next()
}, 100)

要想有随机的效果,其实可以这样考虑:

  1. 先随机排序50条目对应序号到一个本地数值对象AList中记录
  2. 从AList中按每次取出3条来切换真正显示的部分
  3. 对AList的访问按循环数组来使用,只需要记录访问到的头索引和AList的长度即可循环进行操作。
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题