2013-03-12 92 views
0

這是如何在陣列搜索的價值存在:CoffeeScript的:搜索具有特定屬性值的對象

words = ["rattled", "roudy", "rebbles", "ranks"] 
alert "Stop wagging me" if "ranks" in words 

我在尋找與指定屬性值對象的存在尋找類似的優雅:

words = [ 
    { id: 1, value: "rattled" }, 
    { id: 2, value: "roudy" }, 
    { id: 3, value: "rebbles" }, 
    { id: 4, value: "ranks" } 
] 
alert "Stop wagging me" if "ranks" in words.value 

但底部的行不起作用。

回答

1

如果你想有1套,你可以做到以下幾點:

alert "Stop wagging me" if do -> return yes for w in words when w.value is 'ranks' 

的優點是,它會遍歷在而不是派生一個新的(內存高效的)數組,並且一旦找到匹配就會停止迭代(CPU效率)。要付出的代價是它的可讀性可能會降低。爲了解決這個問題,最好的辦法可能是製作你自己的效用函數:

inObjectMember = (obj, key, value) -> 
    for o in obj when o[key] is value 
    return yes 

alert "Stop wagging me" if inObjectMember words, 'value', 'ranks' 
1

我只是嘗試下,它的工作對我來說:

alert "Stop wagging me" if "ranks" in (word.value for word in words) 
+0

從這個問題我可以看出,你每創建一個新數組需要檢查存在,如果陣列變大或者在任何實質負載下都非常昂貴。 – matehat 2013-03-12 15:50:25

相關問題