2015-10-04 25 views
0

我想在我的項目中實現這個代碼:http://jsfiddle.net/wQysh/351/_.find從underscorejs到JQuery

一切除了線細:

t = _.findWhere(sc, { id : Number(a.trim()) }); 

他們使用underscorejs,我不想使用另一個lib這個翻譯成JQuery的。

我通過DOC去了,它說:

findWhere_.findWhere(列表屬性)

看起來列表並返回匹配所有的鍵 - 值對列出的第一個值屬性中。

如果未找到匹配項,或者列表爲空,則返回undefined。

但是我仍然對此感到困惑,因爲我不確定要返回什麼(作爲第一個值)。任何人都可以給我一個JQuery替代該行?

在此先感謝..

+0

沒有jQuery的選擇,你可以在純醇」的JavaScript實現findWhere。 –

+0

即使JavaScript會..但我怎麼辦? –

+0

你究竟在哪裏堅持你的嘗試? –

回答

1

如果不這樣做的_.findWhere()的泛用性,你可以使用一個簡單的循環while和ID進行比較的數值(fiddle):

t = 0; // t is used as a counter 
aValue = Number(a.trim()); // assign the value to a variable instead of iterating it 
while (t < sc.length && sc[t].id !== aValue) { t++; }; // find the index where the id is the as the aValue 

t < sc.length && toSet.push(sc[t]); // if t is less the sc.length we found the item in the array 

如果你需要一個findWhere沒有下劃線試試這個gist

+0

謝謝!有用 –

0

我也在我的項目中使用了這個例子。還需要使用JQuery而不是Underscore。

這裏是我的解決方案:

t = sc.filter(function (el) { return el.id === a }); 

它的工作非常適合我。

如果您使用的ID號,你也可以轉換爲整數

t = sc.filter(function (el) { return el.id === parseInt(a, 10) });