课程表

CoffeeScript 语法

CoffeeScript 类和对象

CoffeeScript 字符串

CoffeeScript 数组

CoffeeScript 日期和时间

CoffeeScript 数学

CoffeeScript 方法

CoffeeScript 元编程

CoffeeScript jQuery

CoffeeScript 正则表达式

CoffeeScript 网络

CoffeeScript 设计模式

CoffeeScript 数据库

CoffeeScript 测试

工具箱
速查手册

对象数组

当前位置:免费教程 » JS/JS库/框架 » CoffeeScript

问题

你想要得到一个与你的某些属性匹配的数组对象。

你有一系列的对象,如:

  1. cats = [
  2. {
  3. name: "Bubbles"
  4. favoriteFood: "mice"
  5. age: 1
  6. },
  7. {
  8. name: "Sparkle"
  9. favoriteFood: "tuna"
  10. },
  11. {
  12. name: "flyingCat"
  13. favoriteFood: "mice"
  14. age: 1
  15. }
  16. ]

你想用某些特征来滤出想要的对象。例如:猫的位置 ({ 年龄: 1 }) 或者猫的位置 ({ 年龄: 1 , 最爱的食物: "老鼠" })

解决方案

你可以像这样来扩展数组:

  1. Array::where = (query) ->
  2. return [] if typeof query isnt "object"
  3. hit = Object.keys(query).length
  4. @filter (item) ->
  5. match = 0
  6. for key, val of query
  7. match += 1 if item[key] is val
  8. if match is hit then true else false
  9. cats.where age:1
  10. # => [ { name: 'Bubbles', favoriteFood: 'mice', age: 1 },{ name: 'flyingCat', favoriteFood: 'mice', age: 1 } ]
  11. cats.where age:1, name: "Bubbles"
  12. # => [ { name: 'Bubbles', favoriteFood: 'mice', age: 1 } ]
  13. cats.where age:1, favoriteFood:"tuna"
  14. # => []

讨论

这是一个确定的匹配。我们能够让匹配函数更加灵活:

  1. Array::where = (query, matcher = (a,b) -> a is b) ->
  2. return [] if typeof query isnt "object"
  3. hit = Object.keys(query).length
  4. @filter (item) ->
  5. match = 0
  6. for key, val of query
  7. match += 1 if matcher(item[key], val)
  8. if match is hit then true else false
  9. cats.where name:"bubbles"
  10. # => []
  11. # it's case sensitive
  12. cats.where name:"bubbles", (a, b) -> "#{ a }".toLowerCase() is "#{ b }".toLowerCase()
  13. # => [ { name: 'Bubbles', favoriteFood: 'mice', age: 1 } ]
  14. # now it's case insensitive

处理收集的一种方式可以被叫做 “find” ,但是像 underscore 或者 lodash 这些库把它叫做 “where” 。

转载本站内容时,请务必注明来自W3xue,违者必究。
 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号