js array split method, custom split length

function:

    function splitArray(arr,size) {
      let result = [];
      while (arr.length > 0) {
        let currentChunk = arr.splice(0, size);
        result.push(currentChunk);
      }

      return result;
    }

Note: The point is to understand that the splice method of an array will change the original array

Algorithm idea: When the length of the original array is greater than 0, the length of the original array is continuously cut to size, until the length of the original array is less than or equal to 0

Example:

    <script>
    let arr=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61]
    console.log(splitArray(arr,30));
    function splitArray(arr,size) {
      let result = [];
      while (arr.length > 0) {
        let currentChunk = arr.splice(0, size);
        result.push(currentChunk);
      }

      return result;
    }
    </script>

 output:

Guess you like

Origin blog.csdn.net/h18377528386/article/details/130155384