鍍金池/ 教程/ HTML/ 對(duì)象數(shù)組
備忘錄模式
解釋器模式
類(lèi)似 Python 的 zip 函數(shù)
類(lèi)變量和實(shí)例變量
提示參數(shù)
指數(shù)對(duì)數(shù)運(yùn)算
檢查變量的類(lèi)型是否為數(shù)組
由數(shù)組創(chuàng)建一個(gè)字符串
生成隨機(jī)數(shù)
刪除數(shù)組中的相同元素
大寫(xiě)單詞首字母
雙向服務(wù)器
類(lèi)的混合
計(jì)算復(fù)活節(jié)的日期
轉(zhuǎn)換弧度和度
找到上一個(gè)月(或下一個(gè)月)
雙向客戶端
橋接模式
嵌入 JavaScript
AJAX
觀察者模式
克隆對(duì)象(深度復(fù)制)
一個(gè)隨機(jī)整數(shù)函數(shù)
清理字符串前后的空白符
歸納數(shù)組
平方根倒數(shù)快速算法
適配器模式
打亂數(shù)組中的元素
將數(shù)組連接
使用數(shù)組來(lái)交換變量
更快的 Fibonacci 算法
服務(wù)器
服務(wù)端和客戶端的代碼重用
客戶端
查找子字符串
策略模式
CoffeeScrip 的 type 函數(shù)
由數(shù)組創(chuàng)建一個(gè)對(duì)象詞典
回調(diào)綁定
工廠方法模式
映射數(shù)組
當(dāng)函數(shù)括號(hào)不可選
生成可預(yù)測(cè)的隨機(jī)數(shù)
不使用 jQuery 的 Ajax 請(qǐng)求
把字符串轉(zhuǎn)換為小寫(xiě)形式
類(lèi)方法和實(shí)例方法
擴(kuò)展內(nèi)置對(duì)象
定義數(shù)組范圍
MongoDB
匹配字符串
創(chuàng)建一個(gè)不存在的對(duì)象字面值
列表推導(dǎo)
比較范圍
修飾模式
檢測(cè)每個(gè)元素
拆分字符串
字符串插值
對(duì)象數(shù)組
去抖動(dòng)函數(shù)
使用 Nodeunit 測(cè)試
SQLite
單件模式
篩選數(shù)組
替換子字符串
數(shù)組最大值
計(jì)算(美國(guó)和加拿大的)感恩節(jié)日期
找到一個(gè)月中的最后一天
計(jì)算兩個(gè)日期中間的天數(shù)
基本的 HTTP 服務(wù)器
把字符串轉(zhuǎn)換為大寫(xiě)形式
使用 HTML 命名實(shí)體替換 HTML 標(biāo)簽
For 循環(huán)
模板方法模式
重復(fù)字符串
使用 Jasmine 測(cè)試
對(duì)象的鏈?zhǔn)秸{(diào)用
數(shù)學(xué)常數(shù)
反轉(zhuǎn)數(shù)組
計(jì)算月球的相位
使用 Heregexes
查找子字符串
生成器模式
遞歸函數(shù)
HTTP 客戶端
創(chuàng)建 jQuery 插件
檢測(cè)與構(gòu)建丟失的函數(shù)
生成唯一ID
命令模式

對(duì)象數(shù)組

問(wèn)題

你想要得到一個(gè)與你的某些屬性匹配的數(shù)組對(duì)象。

你有一系列的對(duì)象,如:

cats = [
  {
    name: "Bubbles"
    favoriteFood: "mice"
    age: 1
  },
  {
    name: "Sparkle"
    favoriteFood: "tuna"
  },
  {
    name: "flyingCat"
    favoriteFood: "mice"
    age: 1
  }
]

你想用某些特征來(lái)濾出想要的對(duì)象。例如:貓的位置 ({ 年齡: 1 }) 或者貓的位置 ({ 年齡: 1 , 最?lèi)?ài)的食物: "老鼠" })

解決方案

你可以像這樣來(lái)擴(kuò)展數(shù)組:

Array::where = (query) ->
    return [] if typeof query isnt "object"
    hit = Object.keys(query).length
    @filter (item) ->
        match = 0
        for key, val of query
            match += 1 if item[key] is val
        if match is hit then true else false

cats.where age:1
# => [ { name: 'Bubbles', favoriteFood: 'mice', age: 1 },{ name: 'flyingCat', favoriteFood: 'mice', age: 1 } ]

cats.where age:1, name: "Bubbles"
# => [ { name: 'Bubbles', favoriteFood: 'mice', age: 1 } ]

cats.where age:1, favoriteFood:"tuna"
# => []

討論

這是一個(gè)確定的匹配。我們能夠讓匹配函數(shù)更加靈活:

Array::where = (query, matcher = (a,b) -> a is b) ->
    return [] if typeof query isnt "object"
    hit = Object.keys(query).length
    @filter (item) ->
        match = 0
        for key, val of query
            match += 1 if matcher(item[key], val)
        if match is hit then true else false

cats.where name:"bubbles"
# => []
# it's case sensitive

cats.where name:"bubbles", (a, b) -> "#{ a }".toLowerCase() is "#{ b }".toLowerCase()
# => [ { name: 'Bubbles', favoriteFood: 'mice', age: 1 } ]
# now it's case insensitive

處理收集的一種方式可以被叫做 “find” ,但是像 underscore 或者 lodash 這些庫(kù)把它叫做 “where” 。