Function: each()
ts
function each<V, K>(collection, callbackfn): boolean;Iterates over a collection and applies a function to each element. 遍历集合并对每个元素应用函数。
This function provides a unified interface for iterating over different types of collections including arrays, objects, Maps, Sets, and strings. The iteration can be stopped early by returning false from the callback. 此函数为遍历不同类型的集合提供统一接口,包括数组、对象、Map、Set和字符串。 可以通过从回调函数返回false来提前停止迭代。
Type Parameters
| Type Parameter | Default type | Description |
|---|---|---|
V | - | The type of values in the collection / 集合中值的类型 |
K extends string | number | number | The type of keys in the collection / 集合中键的类型 |
Parameters
| Parameter | Type | Description |
|---|---|---|
collection | Collection<V, K> | The collection to iterate over / 要遍历的集合 |
callbackfn | (value, key, collection) => boolean | void | undefined | The function to apply to each element / 应用于每个元素的函数 |
Returns
boolean
True if all iterations complete, false if stopped early / 如果所有迭代完成返回true,如果提前停止返回false
Example
typescript
// Array — stop early by returning false
each([1, 2, 3, 4, 5], (value, index) => {
console.log(index, value)
return value < 3
})
// Object
each({ name: 'John', age: 30 }, (value, key) => {
console.log(key, value)
})
// Map
each(new Map([['a', 1], ['b', 2]]), (value, key) => {
console.log(key, value)
})
// Set
each(new Set([1, 2, 3]), (value) => {
console.log(value)
})Since
1.0.0