我最近正在尝试学习fp,并尝试在我的项目中使用ramda.js,但我遇到了一些问题。
我的代码的目标是希望将带有一些初始值的result prop添加到list数组的每个元素中,但它并没有像预期的那样工作。
下面是我的代码:
var list = [{name: 'foo'}, {name: 'bar'}, {name: 'baz'}]
var list1 = R.clone(list)
var getResultList = R.times(R.identity)
// what's the difference between them ??
// it worked as expected if I wrap assoc fn into arrow function and transfer it to fn
var mapAssocResult= R.map(e=> R.assoc('result', getResultList(2), e))
// it didn't work as expected if I just transfer it as param of map fn
var mapAssocResult1= R.map(R.assoc('result', getResultList(2)))
list = mapAssocResult(list)
list1 = mapAssocResult1(list1)
list[0].result === list[1].result //false
list1[0].result === list1[1].result // true
// it seems that all result props point to the same array reference, but why?
使用Ramda.js有什么需要注意的吗?
也许我使用Ramda.js的想法是完全错误的,那么有没有更合理的方法来实现我在Ramda.js中的目标呢?
非常感谢。
发布于 2017-02-19 13:28:08
您看到的结果是由于在R.map(R.assoc('result', getResultList(2)))中过早地计算了getResultList(2)。这最终等同于R.map(R.assoc('result', [0, 1])),它将为每个元素的result属性分配相同的[0, 1]实例。
额外的箭头函数可防止在将映射函数应用于数组的每个元素之前计算getResultList(2),从而为每个result属性生成一个新的且唯一的[0, 1]实例。
https://stackoverflow.com/questions/42323352
复制相似问题