【发布时间】:2015-12-10 10:20:07
【问题描述】:
主要目标是通过任何给定属性过滤数组中的重复项。我尝试使用的解决方案是在js中@https://stackoverflow.com/a/31194441/618220
我尝试在咖啡脚本中实现它。一切都很好,除了功能的范围。我不希望从外部调用 _indexOfProperty 函数 - 因为它在所有其他上下文中都没用。但是如果我将它 private (通过在声明中删除 @),我不能从 inputArray.reduce
中调用它我的咖啡代码如下所示:
Utils = ->
@filterItemsByProperty= (inputArray,property)=>
if not _.isArray inputArray
return inputArray
r = inputArray.reduce(((a,b,c,d,e)=>
if @._indexOfProperty(a,b,property) < 0
a.push(b)
a
),[])
r
@_indexOfProperty= (a,b,prop) ->
i = 0
while i< a.length
if a[i][prop] == b[prop]
return i
i++
-1
return
window.utils = Utils
这是我从其他地方调用它的方式:
App.utils.filterItemsByProperty(personArray,"name")
现在,任何人都可以这样做:
App.utils._indexOfProperty(1,2,3)
如何修改咖啡来阻止这种情况?
【问题讨论】:
标签: javascript arrays coffeescript scope hoisting