什么是查询在JavaScript数组得到的只是从中我想要的物品的最佳方式? [英] What's the best way to query an array in javascript to get just the items from it I want?

查看:109
本文介绍了什么是查询在JavaScript数组得到的只是从中我想要的物品的最佳方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的数组(刚刚超过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,你可以找到在过滤器方法的实现<一个href=\"https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/filter\">https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/filter

更新

Speed​​wise有一个<击>巨大在测试中出现错误的)从正常回路(的根据浏览器的区别的)..看一看这个小测试,我在 http://jsperf.com/array做-filter-VS环/ 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆