-2
 ["2013 Sea Ray 190 Sport",
  "2013 Sea Ray 205 Sport",
  "2013 Sea Ray 210 SLX",
  "2013 Sea Ray 220 Sundeck",
  "2013 Sea Ray 220 Sundeck Outboard"]

我想遍历数组中的所有对象并列出所有仅包含“Sport”一词的对象,在这种情况下,我应该只返回以下列表

 ["2013 Sea Ray 190 Sport",
  "2013 Sea Ray 205 Sport"]

我怎样才能使用 underscore.js 做到这一点?

4

3 回答 3

1

你想JavaScript吗?

function sift(element) {
  return element.match(/sport/);
}

var arr = ["spam", "spam", "nice sport", "bad sport", "spam"];
var filtered = arr.filter(sift);
alert(filtered);

当心@评论,它在我可爱的人中不起作用IE :(

于 2013-09-06T14:11:30.750 回答
1

使用_.filter的下划线解决方案

var data = ["2013 Sea Ray 190 Sport",
  "2013 Sea Ray 205 Sport",
  "2013 Sea Ray 210 SLX",
  "2013 Sea Ray 220 Sundeck",
  "2013 Sea Ray 220 Sundeck Outboard"];

var result = _.filter(data, function(string) {
    return string.indexOf('Sport') != -1;
});
于 2013-09-06T14:13:30.853 回答
0
// like this:
Array.prototype.filterbystr = function ( str ) {
    var out = [];
    for ( var i = 0, l = this.length; i < l; i++ ) {
        if ( Object.prototype.toString.call( this[i] ) === "[object String]" ) {
            ( this[i].indexOf( str ) !== -1 )
            && out.push( this[i] );
        }
    }
    return out;
};
[
  "2013 Sea Ray 190 Sport",
  "2013 Sea Ray 205 Sport",
  "2013 Sea Ray 210 SLX",
  "2013 Sea Ray 220 Sundeck",
  "2013 Sea Ray 220 Sundeck Outboard"
].filterbystr("Sport");
//
// ["2013 Sea Ray 190 Sport", "2013 Sea Ray 205 Sport"]
//
于 2013-09-06T14:20:58.810 回答