简体   繁体   English

如何制作可以过滤字符串和数字值的Scfilter?

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

Javascript(coffescript): 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)

I wanna change this line " return true for att, value of el when typeof(value) is 'string' and doesMatch(value) and att isnt '$$hashKey' " to make is possible to filter number and string values. 我想更改此行“ 当typeof(value)为'string'和dosMatch(value)且att为not'$$ hashKey'时,对于att,el的值返回true,从而可以过滤数字和字符串值。

This could be easily answered by fixing the conditional logic, but then it will get difficult to read. 通过修复条件逻辑可以很容易地回答这一问题,但随后将很难阅读。 Instead I'll show you some nicer ways of expressing the condition which you are running in a loop: 相反,我将向您展示一些更好的方式来表达您正在循环中运行的条件:

return true for att, value of el when typeof(value) is 'string' and doesMatch(value) and att isnt '$$hashKey'

This is the equivalent of: 这等效于:

for att, value of el
  return true if typeof(value) is 'string' and doesMatch(value) and att isnt '$$hashKey'

The doSomething() for X of/in Y when condition syntax is a shorthand which I would suggest only to use if the function fits on a single line without becoming unwieldy. doSomething() for X of/in Y when condition语法是一种简写形式doSomething() for X of/in Y when conditiondoSomething() for X of/in Y when condition仅在函数适合单行且不会变得笨拙时才建议使用。

The above could be made a little more legible by skipping over any fields which you don't want to check: 通过跳过您不想检查的任何字段,可以使上面的内容更加清晰:

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) 

Now to extend it to search for numbers is much easier: 现在,将其扩展为搜索数字要容易得多:

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) 

Take a look at the little book of coffeescript , specifically the idioms as they explain a lot of how comprehensions work in coffeescript 看一本关于咖啡文字的小书 ,特别是这些成语,因为它们解释了很多理解如何在咖啡文字中发挥作用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM