["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进行此操作?
答案 0 :(得分: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
:(
答案 1 :(得分: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;
});
答案 2 :(得分: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"]
//