简体   繁体   English

检查一个数组元素是否包含字符串

[英]Check if ONE array element contains a string

Is it possible to search for a string within each element of an array. 是否有可能在数组的每个元素内搜索字符串。

So if I have 所以如果我有

var arr =["select 1", "select 2", "unselect 1"];

I want to see which array elements have "1" in them then remove the ones that dont. 我想查看哪些数组元素中包含“ 1”,然后删除那些不包含的元素。 This is the code I have but it is not working. 这是我的代码,但无法正常工作。

var RowNum = ( $('table.input-table > tbody > tr').length);
var type = [];
for(var i=0; i<=(RowNum - 1); i++){
    type.push( $("table.input-table > tbody > tr").eq(i).html());
};
alert(type.length);

for(var i = (type.length - 1); i >= 0 ; i--){
    var SpliceVal = 0;

    for(var ii = 0; ii <= (Req.length -1); ii++){
        if(type[i].indexof(Req[ii]) == -1){
            SpliceVal += 1;    
        };  
    };

    if(SpliceVal == Req.length){
        type.splice(i, 1);
    };
};
alert(type.length);

The first alert(type.length); 第一个警报(type.length); returns a 7. Req.length = 3 返回7。Req.length = 3

The second alert(type.length); 第二个警报(type.length); should return a 3 应该返回3

The code will partially run until I get to the line: 该代码将部分运行,直到我上线为止:

if(type[i].indexof(Req[ii]) == -1)

I get an error saying TypeError: type[i].indexof is not a function 我收到一条错误消息,提示TypeError:type [i] .indexof不是函数

Any help is appreciated 任何帮助表示赞赏

I would use filter; 我会使用过滤器;

var containsOne = function(el) {

   return el.indexOf('1') !== -1;
}

var filtered = ['select', 'select', 'select1'].filter( containsOne );

//returns 'select1'

http://jsfiddle.net/8vmjb1Lt/ http://jsfiddle.net/8vmjb1Lt/

If you are dead set on using splice instead of another method: 如果您不习惯使用接合而不是其他方法:

var arr =["select 1", "select 2", "unselect 1", "uneselect 2", "select 1"];

for (var i = 0; i < arr.length; i++) {
    if (arr[i].indexOf("1") > -1) {
        arr.splice(i, 1);
        if (i !== 0) {i--;}
    }
}

Updated JSFIddle . 更新了JSFIddle

This will modify the original array 这将修改原始数组

Here's the exact thing you need. 这正是您需要的东西。 Use jquery grep() function by which you can get the list of elements that satisfy the your condition as shown below: 使用jquery grep()函数,通过该函数可以获得满足您的条件的元素列表,如下所示:

// Original array
var arr =["select 1", "select 2", "unselect 1"];

// Here, after executing this function your original array will have only
// elements having 1 in them
arr = jQuery.grep(arr, function(value) {
           if(value.indexOf("1") > 0){
              return true;
           }else{
              return false;
           }
      });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM