ramda.js 的代码有什么区别?
what is the difference in the codes with ramda.js?
我最近在尝试学习 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中有没有更合理的方法来实现我的目标?
非常感谢。
您看到的结果是由于 getResultList(2)
在 R.map(R.assoc('result', getResultList(2)))
中过早评估所致。这最终等效于 R.map(R.assoc('result', [0, 1]))
,它将相同的 [0, 1]
实例分配给每个元素的 result
属性.
在将映射函数应用于数组的每个元素之前,额外的箭头函数会阻止对 getResultList(2)
求值,从而为每个 [=14= 生成一个新的且唯一的 [0, 1]
实例] 属性.
我最近在尝试学习 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中有没有更合理的方法来实现我的目标?
非常感谢。
您看到的结果是由于 getResultList(2)
在 R.map(R.assoc('result', getResultList(2)))
中过早评估所致。这最终等效于 R.map(R.assoc('result', [0, 1]))
,它将相同的 [0, 1]
实例分配给每个元素的 result
属性.
在将映射函数应用于数组的每个元素之前,额外的箭头函数会阻止对 getResultList(2)
求值,从而为每个 [=14= 生成一个新的且唯一的 [0, 1]
实例] 属性.