如何在Ramda.map中访问迭代索引 [英] How can I access iteration index in Ramda.map

查看:68
本文介绍了如何在Ramda.map中访问迭代索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我曾经写过类似的东西

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

与lodash.通常我不需要index,但有时它很有用.

with lodash. Usually I don't need index but sometimes it's useful.

我现在要迁移到Ramda:

I'm migrating to Ramda now:

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

indexundefined.当然,我可以在上限范围内创建变量index,并在map主体中每次将其递增,但是从FP的角度来看,Ramda代表的观点有点不对.那么,是否有任何构建迭代索引的方法?

index is undefined. Sure, I can create variable index in upper scope and increment it every time in map body but it's kinda wrong from FP point of view that Ramda stands for. So is there's any build in way of getting iteration index?

推荐答案

查看 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.

例如,这会将Ramda的简单地图功能变成更类似于Array.prototype.map的功能.请注意,这仅适用于以迭代回调函数为第一个参数且列表为最后一个参数的函数. (如果未使用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']

这篇关于如何在Ramda.map中访问迭代索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆