js 数组中的 IndexOf 元素使用下划线或 jquery 使用真值函数
我需要与 Underscore 的 find 基本相同的功能,但结果是元素的索引(而不是元素本身) )。
据我所知,Underscore 的 indexOf 寻找一个值并且不接受函数。 jQuery 的 inArray 函数也存在同样的问题。
我想出了以下实现,但我不确定它是最有效的:
function myIndexOf(arr, filter) {
var index;
$.each(arr, function (i, elt) { if (filter(elt)) { index=i; return false; } });
return index;
}
I need basically the same functionality as Underscore's find but with the index of the element as a result (and not the element itself).
As far as I know, Underscore's indexOf looks for a value and doesn't take a function. Same problem for jQuery's inArray function.
I came up with the following implementation, but I'm not sure it is the most efficient:
function myIndexOf(arr, filter) {
var index;
$.each(arr, function (i, elt) { if (filter(elt)) { index=i; return false; } });
return index;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
_.findIndex
可在 Lo-Dash 和 Underscore.js:_.findIndex
is available in Lo-Dash and Underscore.js:这是一个简单的实现:
它将适用于具有 length 属性的任何可索引对象,并且您可以传递
filter(element, index, collection) 形式的复杂过滤器函数代码>(可选参数)。
Here is a simple implementation:
It will work on any indexable object that has a length property, and you can pass a complex filter function of the form
filter(element, index, collection)
(optional parameters).Underscore 使用以下实现:
它依次调用
_.any
,后者又调用_.each
,后者又调用Array.prototype.forEach
。效率并不完全是游戏的名称。它更多的是关于实用性。如果您知道您正在处理数组或类似数组的对象,则可以使用@Thor84no 的解决方案并简单地循环遍历数组,直到满足过滤条件。如果没有,并且您可能也在处理对象,我只需将 _.find 重写为 _.findIndex 并使用
result = index;
。Underscore uses the following implementation:
This in turn calls,
_.any
, which calls_.each
, which callsArray.prototype.forEach
. Efficiency isn't exactly the name of the game. It is more about utility.If you know for a fact that you are dealing with an array or array-like object, you can use @Thor84no's solution and simply loop through the array until your filter condition is met. If not, and you may be dealing with objects as well, I would simply rewrite _.find as _.findIndex and use
result = index;
.您可以使用局部变量来获取它,如下所示:
Viola。您获得了索引和匹配值。如果迭代器到达末尾,索引将变为 -1,如果命中匹配项,它将在该索引上短路。
You can just use a local variable to get that like so:
Viola. You got the index AND the matching value. If the iterator reaches the end, the index goes to -1, and if you hit a match, it short-circuits on that index.
自己执行 for 循环并在找到索引后使用
break;
(或return
)离开循环会更有效。It would be more efficient to do the for loop yourself and use
break;
(orreturn
) to leave the loop once you've found the index.