繁体   English   中英

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

[英]Difficulty returning an array of indexes of each element from an array that matches search term

嗨,我真的很努力地为一个函数编写代码,该函数“当匹配搜索词时,从已经填充的包含字符串的数组中返回索引数组”。 因此,如果搜索词与数组元素中的单词或字符匹配,无论其顺序如何,它都应返回这些单词在数组中显而易见的索引。 不使用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]

抱歉,如果我没有很好地解释这一点,请多谢您的帮助。 谢谢。

尝试这个:

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中包含搜索词的所有元素的索引。

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

===更新===

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

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

如果我正确理解您的问题...

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

您没有提到搜索是否区分大小写,但是假设是我将搜索结果放在此处

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

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

暂无
暂无

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

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