我目前正在尝试使用搜索函数,该函数在数组中搜索字符串并返回与字符串匹配的数组中位置的索引。
例如:
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
目前我有它通过使用仅输出1值
document.getElementById("result").innerHTML=
但我希望它返回多个结果
最佳答案
如果您编写自己的函数,则应该能够索引的return an array:
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;
}
然后,您可以组合数组值并将其放入结果位置,如@AnthonyGrist所建议:
document.getElementById('result').innerHTML = indicesOf(input, value).join(', ');
关于javascript - 搜索功能返回多个结果,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26302032/