对于使用jQuery JavaScript的价值有效的搜索阵列 [英] Javascript efficient search array for value with jQuery
问题描述
有在我的JavaScript知识,这里的差距。我要搜索对象值的数组为一个特定的值并返回。
There's a gap in my JavaScript knowledge here. I want to search an array of objects values for a particular value and return it.
有关我一直在写JavaScript的这一年里,我一直在执行这样的:
For the year I have been writing JavaScript, I have been implementing it like this:
var itemClicked = (function(){
var retval;
//Note self.inventory.itemsArray is an array of JS objects
$(self.inventory.itemsArray).each(function(i){
if(parseInt(this.id) === parseInt(idOfItem)){
retval = this;
return false;
}
});
return retval;
})();
它的工作原理,但我敢肯定的东西还有一个更优雅的方式。请告诉我!
It works, but I'm sure as anything there is a more elegant way. Tell me please!
编辑 - 解决方案
由于@gdoron下面他的回答。
Thanks to @gdoron with his answer below.
var myVar = $(self.owner.itemsArray).filter(function(){
return parseInt(this.id) == parseInt(recItemID);
}).get(0);
请注意:获得(0)
被加在最后,因为myVar的包装为jQuery对象。
Note: .get(0)
was added at the end because myVar is wrapped as a jQuery object.
推荐答案
这种情况的本地jQuery的功能是 过滤器
:
The native jQuery function for this is filter
:
$(data).filter(function(){
return this.id == "foo";
});
这比code你有更重要的了很多更具可读性短。结果
关于效率,它会遍历集合中的所有元素找到尽可能多的比赛,但我很难相信这将是你的应用程序的瓶颈,不注重微观的优化即可。
我建议你阅读有关这是更快埃里克·理柏博客。
I suggest you read Eric Lipper blog about Which is faster.
您也可以使用 的grep
由@Mattias Buelens建议:
You can also use grep
as suggested by @Mattias Buelens:
$.grep(data, function(ele){
retun ele.id == "foo";
});
这篇关于对于使用jQuery JavaScript的价值有效的搜索阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!