简体   繁体   English

搜索功能返回多个结果

[英]Search function return multiple results

I'm currently trying to make a search function that searches an array for a string and returns the index of the location in the array for which it matches the string. 我目前正在尝试使用搜索函数,该函数在数组中搜索字符串并返回与字符串匹配的数组中位置的索引。

Ex: 例如:

Array: [1,2,3,4,5,2,3,1,6,5,2]
Search input: 3
Output: 
2
6

Search input: 2
Output:
1
5
10

Currently i have it outputting only 1 value by using 目前我有它通过使用仅输出1值

document.getElementById("result").innerHTML=

But I want it to return multiple results 但我希望它返回多个结果

If you write your own function, you should be able to return an array of indices: 如果您编写自己的函数,则应该能够返回索引数组

function indicesOf(input, value) {
    var indices = new Array();
    for (var i = 0; i < input.length; i++) {
        if (input[i] == value)
            indices.push(i);
    }
    return indices;
}

Then you can combine the array values and put them into the result location, as suggested by @AnthonyGrist: 然后,您可以组合数组值并将其放入结果位置,如@AnthonyGrist所建议:

document.getElementById('result').innerHTML = indicesOf(input, value).join(', ');

我不确定这是否是您要的,但是如果您想从DOM中返回具有给定选择器的所有对象(而不是作用于并返回过滤的javascript数组),则可以使用document.querySelectorAll(<your_selector_here>) - 有关MDN的更多信息,请点击此处

You can do this 你可以这样做

var arr = [1,2,3,4,5,2,3,1,6,5,2];
arr.map(function(x, i){
   return x == 3 ? i : null;
}).filter(Number); // get indexes

The above maps and filters out the index. 上面映射并过滤了索引。 Then it is simply a matter of joining it 然后,只需加入它即可

document.getElementById("result").innerHTML= arr.join("<br />");

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

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