的Javascript(coffescript):
.filter "scFilter", () ->
(collection, search) ->
return collection unless search
regexp = createAccentRegexp(search)
doesMatch = (txt) -> (''+txt).match(regexp)
collection.filter (el) ->
if typeof el == 'object'
return true for att, value of el when typeof(value) is 'string' and doesMatch(value) and att isnt '$$hashKey'
else
doesMatch(el)
我想更改这一行“返回true为att,当typeof(value)为'string'且elMatch(值)和att不是'$$ hashKey'时,el的值为”可以过滤数字和字符串值。
答案 0 :(得分:0)
通过修复条件逻辑可以很容易地解决这个问题,但之后会很难阅读。相反,我将向您展示一些更好的方式来表达您在循环中运行的条件:
return true for att, value of el when typeof(value) is 'string' and doesMatch(value) and att isnt '$$hashKey'
这相当于:
for att, value of el
return true if typeof(value) is 'string' and doesMatch(value) and att isnt '$$hashKey'
doSomething() for X of/in Y when condition
语法是一种简写,我建议只在函数适合单行而不变得笨拙时使用。
通过跳过您不想检查的任何字段,可以使上述内容更加清晰:
for att, value of el
# first filter out any unwanted values
continue unless typeof(value) is 'string'
continue if att is '$$hashKey'
# Then run you function for checking for matching search terms
return true if and doesMatch(value)
现在扩展它以搜索数字更容易:
for att, value of el
# first filter out any unwanted values
continue unless typeof(value) in ['string', 'number']
continue if att is '$$hashKey'
# Then run you function for checking for matching search terms
return true if and doesMatch(value)
看看the little book of coffeescript,特别是idioms,因为他们解释了很多理解在coffeescript中的作用