大网数据广告活动
Web 标准与前端开发

Iterator.prototype.chunks()

· 52CE 我爱测

The **`chunks()`** method of Iterator instances returns a new iterator helper object that splits the elements from the original iterator into consecutive array chunks. Each time the helper is iterated, it gets the specified number of elements from the underlying iterator and yiel

The chunks() method of Iterator instances returns a new iterator helper object that splits the elements from the original iterator into consecutive array chunks. Each time the helper is iterated, it gets the specified number of elements from the underlying iterator and yields them together.

To yield overlapping sequences (i.e., sliding window), see Iterator.prototype.windows().

Syntax

chunks(chunkSize)

Parameters

  • chunkSize
    • : The number of elements in each chunk. Must be a positive integer less than 2<sup>32</sup> (the maximum array length).

Return value

A new iterator helper object. Each time the returned iterator helper's next() method is called, the original iterator is advanced by chunkSize elements, and those elements are yielded together as an array.

If the original iterator has some but fewer than chunkSize elements remaining, those elements are still yielded as an array (so the length is less than chunkSize), and the iterator helper will be immediately completed the next time next() is called.

If the original iterator has no elements remaining, the iterator helper is immediately completed without yielding an empty array.

Exceptions

  • TypeError
    • : Thrown if chunkSize is not an integer.
  • RangeError
    • : Thrown if chunkSize is less than 1 or greater than 2<sup>32</sup>-1.

Examples

Printing elements in a grid

The following example creates an iterator that yields terms in the Fibonacci sequence. Then, they are printed in a grid layout by retrieving 5 elements each time.

function* fibonacci() {
  let current = 1;
  let next = 1;
  while (true) {
    yield current;
    [current, next] = [next, current + next];
  }
}

const rows = fibonacci().chunks(5);

for (const row of rows.take(5)) {
  console.log(row.join("\t"));
}

Output:

1       1       2       3       5
8       13      21      34      55
89      144     233     377     610
987     1597    2584    4181    6765
10946   17711   28657   46368   75025

Specifications

Browser compatibility

See also

来源:MDN Web Docs / Mozilla 贡献者 · 作者与贡献记录 · CC BY-SA 2.5。离线整理了版式、链接和媒体显示。

资料来源与适用范围

资料来源
MDN Web Docs / Mozilla 贡献者
适用范围
请按文中版本与环境说明核对
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 2.5

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。