难以从匹配搜索项的数组返回每个元素的索引数组

时间:2011-11-13 16:09:02

标签: arrays function pattern-matching javascript

您好我正在努力为一个函数制作代码,该函数'返回包含字符串的已填充数组的索引数组,当它与搜索词匹配时'。 因此,如果搜索项匹配数组元素中的一个或多个字符而不管其顺序如何,则应返回这些字在数组中显而易见的索引。不使用jquery grep功能。 这是一些代码来说明我的意思。

array_test = ["Today was hot","Tomorrow will be hot aswell", "Yesterday the weather was not so good","o1234 t12345"]

function locateSearch(array_test,searchTerm){ 
var myArray = [];

for(i=0;i<array_test.length;i++){ 
if(...) // what should i be testing here, this is where i have been going wrong... 

myArray[myArray.length] = i; 
} 
 return myArray;  
}

document.write(locateSearch,'ot') //this should return indexes [0,1,2,3]

对不起如果我没有这么好解释,请感谢您的帮助。谢谢。

4 个答案:

答案 0 :(得分:0)

试试这个:

array_test = ["Today was hot","Tomorrow will be hot aswell", "Yesterday the weather was not so good","o1234 t12345"]

function locateSearch(array_test,searchTerm) { 
    var myArray = [];

    for(i=0;i<array_test.length;i++) { 
        if(array_test[i].indexOf(searchTerm) != -1) // what should i be testing here, this is where i have been going wrong... 

        myArray.push(i); 
    } 
    return myArray;  
}

document.write(locateSearch,'ot') //this should return indexes [0,1,2,3]

这将返回array_test中包含搜索词的所有元素的索引。

答案 1 :(得分:0)

array_test = ["Today was hot","Tomorrow will be hot aswell", "Yesterday the weather was not so good","o1234 t12345"];

function locateSearch(array_test,searchTerm){
    searchTerm = searchTerm.toLowerCase();
    var myArray = [];
    for(var i = 0; i < array_test.length; i++){
        for(var j = 0; j < searchTerm.length; j++) {
            if(array_test[i].toLowerCase().indexOf(searchTerm[j]) >= 0) {
                myArray.push(i);
                break;
            }
        }
    }
    return myArray;  
}

alert(locateSearch(array_test, 'To').toString());

另见jsfiddle

=== UPDATE ===

如果每个字符都必须在同一个字符串中:

array_test = ["Today was hot","Tomorrow will be hot aswell", "Yesterday the weather was not so good","o1234 t12345"];

function locateSearch(array_test,searchTerm){
    searchTerm = searchTerm.toLowerCase();
    var myArray = [];
    var bFound;
    for(var i = 0; i < array_test.length; i++){
        bFound = true;
        for(var j = 0; j < searchTerm.length; j++) {
            if(array_test[i].toLowerCase().indexOf(searchTerm[j]) == -1) {
                bFound = false;
                break;
            }
        }
        if (bFound) {
            myArray.push(i);
        }
    }
    return myArray;  
}

alert(locateSearch(array_test, 'es').toString());

另请参阅我更新的jsfiddle

答案 2 :(得分:0)

如果我理解你的问题......

if(array_test[i].indexOf(searchTerm).toLowercase() != -1)
    myArray.push(i);

你没有提到搜索是否区分大小写,但假设我把它扔在那里

答案 3 :(得分:0)

如果您需要测试不区分大小写,请使用regEx匹配方法而不是indexOf()

所以... if(array[i].match(/searchTerm/i) != null){ myArray.push(i) }