查找字符串中指定字符的所有索引 [英] Finding all indexes of a specified character within a string
问题描述
例如,如果我在变量中有剪刀
,并想知道所有出现的字母的位置s
,它应该打印出来 1,4,5,8
For example if I had "scissors"
in variable and wanted to know the position of all occurrences of the letter "s"
, it should print out 1, 4, 5, 8
我该如何做到这一点JavaScript以最有效的方式?我不认为循环整体是非常有效的
How can I do this in JavaScript in most efficient way? I don't think looping through the whole is terribly efficient
推荐答案
一个简单的循环效果很好:
A simple loop works well:
var str = "scissors";
var indices = [];
for(var i=0; i<str.length;i++) {
if (str[i] === "s") indices.push(i);
}
现在,您表明您想要1,4,5,8。这将给你0,3,4,7,因为索引是从零开始的。所以你可以添加一个:
Now, you indicate that you want 1,4,5,8. This will give you 0, 3, 4, 7 since indexes are zero-based. So you could add one:
if (str[i] === "s") indices.push(i+1);
现在它会给你预期的结果。
and now it will give you your expected result.
小提琴可以在这里看到。
我不认为循环整体是非常有效的
I don't think looping through the whole is terribly efficient
就性能而言,在你开始遇到问题之前,我不认为这是你需要非常担心的事情。
As far as performance goes, I don't think this is something that you need to be gravely worried about until you start hitting problems.
这是一个 jsPerf 测试比较各种答案。在Safari 5.1中,IndexOf表现最佳。在Chrome 19中,for循环是最快的。
Here is a jsPerf test comparing various answers. In Safari 5.1, the IndexOf performs the best. In Chrome 19, the for loop is the fastest.
这篇关于查找字符串中指定字符的所有索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!