JS里循环截取(slice)数组中固定长度,获取新数组。

javascript/jquery

浏览数:430

2020-5-23

应用场景:换一批功能

<div class="search" onclick="handleClickChange()">换一批</div>
<ul></ul>

<script>
  let textAllData = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  let page = 0
  function handleClickChange () {
    let res = changeFun(textAllData, 4)
    let str = ''
    res.forEach(item => {
      str += `
        <li>${item}</li>
      `
    })
    document.querySelector('ul').innerHTML = str
  }
  function changeFun (allData, n) {
    let length = allData.length
    let result = length - page
    let newArr = []
    if (result > 0 && result < n) {
      newArr = [...allData.slice(length - result, length), ...allData.slice(0, n - result)]
      page = n - result
    } else if (result >= n) {
      newArr = allData.slice(page, page + n)
      page += n
    } else {
      page = 0
      newArr = allData.slice(page, page + n)
    }
    return newArr
  }
</script>

作者:familyAboveAll