在 javascript 中查询数组以从中获取我想要的项目的最佳方法是什么? [英] What's the best way to query an array in javascript to get just the items from it I want?
问题描述
我有一个这样的数组(只有 3000 多个对象,而不是这里的 3 个):
I have an array like this (with just over 3000 objects instead of the 3 here):
items = [{name:'charlie', age:'16'}, {name:'ben', age:'18'}, {name:'steve', age:'18'}]
返回仅包含 18 岁人群对象的数组的最佳方法是什么?所以我想要:
What's the best way to return an array with just the objects of people who are 18? So I want:
items = [{name:'ben', age:'18'}, {name:'steve', age:'18'}]
我能想到的最好的就是这个(使用 jQuery):
The best I can think of is this (using jQuery):
newArray = []
$.each(items, function(index, item) {
if(item.age=='18') {
newArray.push(item)
}
})
考虑到有 300 万个对象,而且我将一次最多进行 50 次这样的比较,这就需要大量循环.有没有更好的办法?
Considering that there's 3000 thousand objects, and also that I'll be doing that comparison up to fifty times in one go, that's a lot of looping. Is there a better way?
推荐答案
可以使用纯javascript
You can use pure javascript
var wanted = items.filter( function(item){return (item.age==18);} );
如果您的浏览器不支持 1.6 版本的 javascript,您可以在 https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/filter
And if your browser does not support the 1.6 version of javascript you can find an implementation of the filter method at https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/filter
更新
Speedwise 有一个巨大 变化的(在测试中出错) 与正常循环的区别(取决于浏览器).. 看看我在 http://做的这个小测试jsperf.com/array-filter-vs-loop/3
Speedwise there is a huge varying (had an error in the test) difference from a normal loop (depending on browser).. Have a look at this little test i made at http://jsperf.com/array-filter-vs-loop/3
这篇关于在 javascript 中查询数组以从中获取我想要的项目的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!