What's the best way to query an array in javascript to get just the items from it I want?

后端 未结 7 1050
悲哀的现实
悲哀的现实 2020-12-13 18:48

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:\'s         


        
7条回答
  •  时光说笑
    2020-12-13 19:13

    You can use pure javascript

    var wanted = items.filter( function(item){return (item.age==18);} );
    

    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


    Update

    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

提交回复
热议问题