如同所有编程语言一样,数组(Array)也是 JavaScript 的一个重要的数据类型,在 ES6 中,更是由 ECMA 官方增强了数组操作的能力。不过即便如此与.NET 平台下的 Linq 方法相较来说,原生的 JavaScript 还是缺少了一些重要的方法。为了在开发 JavaScript 时也能使用这些方法,我写了一个轻量的组件增强数组的能力。

组件名为 luckystarry-collections,代码已托管在 Github:https://github.com/LuckyStarry/luckystarry-collections

除了对 Array 对象做出增强之外,组件还提供了 IEnumerable<T> 接口,下面给出几个使用的简单示例:

映射(Select

这个方法的作用是将一个集合中的每个对象,根据指定的方法依次顺序的映射成另一个对象,这个方法类似于 map 方法,不同的是如果使用组件的话,除了 Array 对象可以使用映射的能力之外,所有集合对象也可以使用映射方法。

方法签名

Select<TResult>(selector: (item: T, index?: number) => TResult): IEnumerable<TResult>

数值运算

[1, 2, 3].Select(x => x * 3);
// [3, 6, 9]

取某个字段

[
  { id: 1, name: "tech" },
  { id: 2, name: "game" },
  { id: 3, name: "life" }
].Select(x => x.name);
// ["tech", "game", "life"]

取最大值(Max

方法如同其名字,是遍历集合中的每一个对象,并根据规则取出最大的那个值。

方法签名

Max(selector?: (item: T) => number): number | null

对数值数值取最大值

[1, 2, 3].Max();
// 3

取某个字段的最大值

[{ id: 1, name: "tech" }, { id: 2, name: "game" }, { id: 3, name: "life" }].Max(
  x => x.id
);
// 3

分组(Group

分组方法是将一个集合中的元素根据某种规则分成多组。

方法签名

GroupBy<TKey, TElement = T>(keySelector: (item: T) => TKey, elementSelector?: (item: T) => TElement, comparer?: IEqualityComparer<TKey>): IEnumerable<IGrouping<TKey, TElement>>

使用元素的值做分组条件

[1, 2, 3].GroupBy(x => x);
// [{ Key: 1, [1] }, { Key: 2, [2] }, { Key: 3, [3] }]

使用元素的某个字段做分组条件

[{ ID: 1, Value: 1 }, { ID: 2, Value: 1 }, { ID: 3, Value: 2 }].GroupBy(
  x => x.Value
);
// [{ Key: 1, [{ ID: 1, Value: 1 }, { ID: 2, Value: 1 }] }, { Key: 2, [{ ID: 3, Value: 2 }] }]

当前站点使用静态 CDN 方式全站页面引入了该组件,如果感兴趣可以尝试按F12简单测试下。