jQuery - 返回包含文本字符串的数组中的所有对象

时间:2014-02-21 20:46:00

标签: javascript jquery arrays

是否可以在数组中搜索一串文本,然后返回包含它的对象的内容?

例如:

<script>
    var itemsArray = ["2Bedroom Ensuite 2Bathroom", "1Bedroom Ensuite 1Bathroom", "3Bedroom 2Bathroom"];
    var searchTerm = 'ensuite';
    var results = $.searchThing('itemsArray', searchTerm);
    document.write(results);
</script>

以上假设的脚本(其中'searchThing'是方法 - 如果存在的话)应该写

2Bedroom Ensuite 2Bathroom
2Bedroom Ensuite 2Bathroom

这是否存在?怎么办呢?

由于

3 个答案:

答案 0 :(得分:7)

您可以使用ES5 Array.prototype.filter方法:

var results = itemsArray.filter(function (elem) {
    return elem.toLowerCase().indexOf(searchTerm) > -1;
});

请注意,较旧的浏览器不支持.filter()方法。支持这些浏览器you can use a polyfill

编辑:您还可以使用jQuery $.grep()实用程序函数:

var results = $.grep(itemsArray, function(elem) {
    return elem.toLowerCase().indexOf(searchTerm) > -1;
}); 

答案 1 :(得分:1)

试试这个

var searchTerm = 'ensuite';
var itemsArray = ["2Bedroom Ensuite 2Bathroom", "1Bedroom Ensuite 1Bathroom", "3Bedroom 2Bathroom"];
for(var i=0;i<itemsArray.length;i++){
 var str=itemsArray[i];
  if(str.indexOf(searchTerm ) >= 0){
   //it contains searchterm do something with it.
  }
}

答案 2 :(得分:1)

这可以用jQuery(有点)来做,但是没有必要使用jQuery。无论如何,这是一个jQuery解决方案

var itemsArray = ['asdf','1234'];
var searchTerm = 'asdf';
var results=[];
$.each(itemsArray, function(i,e){
    if(e.indexOf('asdf') > -1)
        results.push(e);
});

我个人更喜欢undefined的解决方案。