在数组Javascript中查找特定单词

时间:2013-09-06 14:01:44

标签: javascript underscore.js

 ["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进行此操作?

3 个答案:

答案 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"]
//