如何访问 Ramda.map 中的迭代索引

How can I access iteration index in Ramda.map

我曾经写过类似的东西

_.map(items, (item, index) => {});

使用 lodash。通常我不需要 index 但有时它很有用。

我现在正在迁移到 Ramda:

R.map((item, index) => {}, items);

indexundefined。当然,我可以在上层范围内创建变量 index 并在 map 主体中每次递增它,但从 Ramda 所代表的 FP 角度来看,这是有点错误的。那么有什么方法可以获取迭代索引吗?

查看 addIndex:

Creates a new list iteration function from an existing one by adding two new parameters to its callback function: the current index, and the entire list.

This would turn, for instance, Ramda's simple map function into one that more closely resembles Array.prototype.map. Note that this will only work for functions in which the iteration callback function is the first parameter, and where the list is the last parameter. (This latter might be unimportant if the list parameter is not used.)

文档中的示例:

var mapIndexed = R.addIndex(R.map);
mapIndexed((val, idx) => idx + '-' + val, ['f', 'o', 'o', 'b', 'a', 'r']);
//=> ['0-f', '1-o', '2-o', '3-b', '4-a', '5-r']

您还可以使用 mapIndexed from Ramda Adjunct,它在后台使用 R.addIndex

R.map function that more closely resembles Array.prototype.map. It takes two new parameters to its callback function: the current index, and the entire list.

RA.mapIndexed((val, idx, list) => idx + '-' + val, ['f', 'o', 'o', 'b', 'a', 'r']);
//=> ['0-f', '1-o', '2-o', '3-b', '4-a', '5-r']

它还提供 reduceIndexed

const initialList = ['f', 'o', 'o', 'b', 'a', 'r'];

reduceIndexed((acc, val, idx, list) => acc + '-' + val + idx, '', initialList);
//=> "-f0-o1-o2-b3-a4-r5"

作为 addIndex 的替代方案,您可以在映射之前使用 toPairs,来自 the documentation:

Converts an object into an array of key, value arrays. Only the object's own properties are used. Note that the order of the output array is not guaranteed to be consistent across different JS platforms.

该文档仅讨论对象,但它同样适用于数组。在您的示例中:

R.map(([index, item]) => {}, R.toPairs(items));

// or, equivalent:

R.compose(
    R.map(([index, item]) => {}),
    R.toPairs,
)(items)

请记住,在每个 index/value 对中,索引始终是第一个元素,因此与 lodash(或本机 Array.prototype.map)相比,顺序是相反的。