coffeeescript:如何声明可以在Array.reduce中使用的私有函数
coffeeescript: how to declare private function that can be used from within Array.reduce?
主要目的是根据任何给定的属性从数组中过滤重复项。我试图使用的解决方案是在js @ https://stackoverflow.com/a/31194441/618220
我尝试在coffeescript中实现它。这一切都很好,除了函数的作用域。我不希望_indexOfProperty函数从外部调用-因为它在所有其他上下文中都是无用的。但是,如果我使私有(通过删除声明中的@),我就不能从 inputararray .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)
如何修改咖啡来阻止这种情况?
只是不要把_indexOfProperty
放在this
/@
上,这样它就不可见了:
Utils = ->
_indexOfProperty = (a,b,prop) ->
i = 0
while i< a.length
if a[i][prop] == b[prop]
return i
i++
-1
@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
return
window.utils = Utils
你能不能删除'@',这次在filterItemsByProperty范围内定义一个局部变量"indexOfProperty"并分配给它"_indexOfProperty"(这样你就可以在reduce()中使用"indexOfProperty")?
@filterItemsByProperty = (inputArray, property) ->
indexOfProperty = _indexOfProperty
if !_.isArray(inputArray)
return inputArray
r = inputArray.reduce(((a, b, c, d, e) ->
if indexOfProperty(a, b, property) < 0
a.push b
a
), [])
r
相关文章:
- 如何为json对象中的段发送array[]
- Array.length似乎不起作用;console.log则显示其他情况
- 如何迭代Array.prototype函数
- Javascript 新的 Array 和 join() 方法
- 对一个对象使用reduce可以返回一个没有't在数组中包含目标字母
- 为什么 Array.prototype.reduce() 不接受 Map 对象作为初始值
- Array.prototype.reduce的实际用途是什么
- 如何在 Indesign 脚本中使用像 Array.reduce() 这样的高阶函数
- Javascript - Reduce and Array
- 在字符串上实现array.protype.reduce()
- 对于Array,使用map()&reduce()而不是javascript中的forEach()
- JavaScript——无法理解数组.地图,Array.reduce
- 理解Array.reduce()和作用域
- 为什么Array.prototype.reduce()不将空数组作为累加器
- 使用Array.reduce得到奇怪的结果
- coffeeescript:如何声明可以在Array.reduce中使用的私有函数
- Array.prototype.reduce与用于过滤和修改数据的简单for循环相比
- Javascript Reduce an empty array
- 与javascript中的Array.reduce()相反
- 递归函数中的Array.prototype.reduce产生了意想不到的结果