开发者

Subsection of an Array in JS/JQuery

I'm looking to extract a subsection of a javascript array of objects based on a certain condition, e.g:

object.property == 2

I know that I could look开发者_Python百科 through and build a new array from the ones that match, but I was wondering whether there was a shorthand for this.


You can use grep().

var arr = [ 1, 2, 3 ];
var subset = $.grep(arr,function(n,i){ return n >= 2 });
// subset = [2, 3]


Use http://api.jquery.com/filter/

e.g.

$(yourCollection).filter(function(){
    return (this.property == 2);
});

EDIT: jsFiddle with both approaches benchmarked: http://jsfiddle.net/StuperUser/6AfQj/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜