Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chunk函数 #99

Open
Sunny-117 opened this issue Nov 3, 2022 · 2 comments
Open

chunk函数 #99

Sunny-117 opened this issue Nov 3, 2022 · 2 comments

Comments

@Sunny-117
Copy link
Owner

No description provided.

@jlx2002
Copy link
Contributor

jlx2002 commented Jan 16, 2023

/*
描述:
    将数组(nums)拆分成多个 size 长度的区块,并将这些区块组成一个新数组。 
    如果nums 无法被分割成全部等长的区块,那么最后剩余的元素将组成一个区块。

示例:
    输入:nums = [1,3,2,5], size = 2

    输出:result = [[1,3], [2,5]] 

    输入:nums = [2,7,11,15,13], size = 3

    输出:result = [[2,7,11], [15,13]]

应用:
    数组分块中重要性在于它可以将多个项目的处理在执行队列上分开,
    在每个项目处理之后,给予其他的浏览器处理机会运行,
    这样就可能避免长时间运行脚本的错误
*/

/**
 * @description: 方法1:循环 每次 + size 后加入result 中
 * @param {*} nums 数组
 * @param {*} size 分割长度
 * @return {*}
 */
function chunk(nums, size = 1) {
  // 获取数组长度
  let length = nums == null ? 0 : nums.length;
  //  检验参数
  if (!length || size < 1) {
    return [];
  }
  // 返回值
  const result = [];
  let index = 0;
  while (index < nums.length) {
    result.push(nums.slice(index, index + size));
    index += size;
  }
  return result;
}
/**
 * @description: 方法2:递归
 * @param {*} nums 数组
 * @param {*} size 分割长度
 * @return {*}
 */
function chunk1(nums, size = 1) {
  // 获取数组长度
  let length = nums == null ? 0 : nums.length;
  //  检验参数
  if (!length || size < 1) {
    return [];
  }
  // 返回值
  const result = [];
  function chunks(array) {
    // 如果不等于0 截取前n个
    result.push(array.slice(0, size));
    // 如果数组长度小于n个
    if (array.length < size) {
      return;
    }
    return chunks(array.slice(size));
  }
  chunks(nums);
  return result;
}

@linlai163
Copy link

这样写简单一点吧。

function chunk(arr, len) {
  const result = []
  let i = 0
  while(i < arr.length) {
    result.push(arr.slice(i, i + len))
    i += len
  }
  return result
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants