我怎样才能制作一个可以过滤字符串和数值的 Scfilter?

How can i make a Scfilter that can filter string and number values?

Javascript(咖啡脚本):

.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)

我想更改此行“return 对 att 为真,当 typeof(value) 为 'string' 且 doesMatch(value) 且 att 不是 '$$ 时 el 的值hashKey'" 可以过滤数字和字符串值。

这可以通过修复条件逻辑轻松解决,但这样会变得难以阅读。相反,我将向您展示一些更好的方式来表达您在循环中 运行 的条件:

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 语法是一个 shorthand 语法,我建议仅在函数适合单行而不变得笨拙时才使用它。

通过跳过您不想检查的任何字段,可以使上面的内容更加清晰:

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, specifically the idioms,因为他们解释了 coffeescript 中理解的很多工作原理