首页 > 解决方案 > 什么是分块[chunked.length - 1]?在这段代码中

问题描述

我在搜索 js 中数组块的其他解决方案时发现了这段代码,但我偶然发现了这部分:const last = chunked[chunked.length - 1];?有人可以解释它的作用吗?

function chunk(array, size) {
      const chunked = [];

      for (let element of array) {
        const last = chunked[chunked.length - 1];

        if (!last || last.length === size) {
          chunked.push([element]);
        } else {
          last.push(element);
        }
      }

      return chunked;
    }

    chunk([1, 2, 3, 4, 5, 6, 7, 8], 3)

    result:
    [[ 1, 2, 3], [4, 5, 6], [7, 8]]

标签: javascript

解决方案


推荐阅读