问题描述
我曾经写过类似的东西
_.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);
index
是undefined
.当然,我可以在上限范围内创建变量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
:
例如,这会将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中访问迭代索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!