_.findWhere 从 underscorejs 到 JQuery

_.findWhere from underscorejs to JQuery

我正在尝试在我的项目中实现此代码:http://jsfiddle.net/wQysh/351/

一切正常,除了以下行:

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

他们使用了 underscorejs,我想在不使用其他库的情况下将其翻译成 JQuery。

我查看了文档并指出:

findWhere_.findWhere(list, properties)

Looks through the list and returns the first value that matches all of the key-value pairs listed in properties.

If no match is found, or if list is empty, undefined will be returned.

但我仍然对此感到困惑,因为我不确定 return 到底是什么(作为第一个值)。谁能给我 JQuery 替代该行的方法?

提前致谢..

如果您不了解 _.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

我在项目中也使用了这个例子。并且还需要使用 JQuery 而不是下划线。

这是我的解决方案:

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

它非常适合我;​​

如果ids使用数字,也可以将a转为整数

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