1

我正在做家庭作业。这是我的问题和尝试的解决方案。

显示字符串“tx_val”中每个字符“e”出现的位置

    tx_val="the quick brown fox jumped over the lazy dogs back";

    os=' ';  //output string
    eloc=' '; 

    for (i=0; i<tx_val.lastIndexOf('e');i++)
     {
    if(tx_val.indexOf('e')!= -1)
        {

            eloc=tx_val.indexOf('e') ; 
            os=os+eloc;
            i++;
        }   

      }         

我的预期结果:2 24 29 34

我的结果:2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2

我不是在寻找答案,而是在寻找一个人来解释为什么我的逻辑不起作用并为我指明正确的方向。

4

4 回答 4

4

当在同一个字符串上使用单个参数调用时,indexOf()每次都会返回相同的索引。

的第一个参数indexOf()是要匹配的子字符串。第二个可选参数是开始搜索表单的索引。除非您传递此参数,否则每次迭代之间的结果都不会改变。

It also is incorrect to assume that the loop should have an i iterator equal to the lastIndexOf() value. That would only make the loop run many redundant iterations, as the number of matches is certainly not equal to the value of the matching indexes (unless the string is only made of e characters). In other words, if you had only one match in index 24, the loop would still repeat 23 times for no reason.

于 2013-10-04T16:05:01.813 回答
2

A better solution might be something like this:

var lastIndex = tx_val.indexOf('e');
while (lastIndex > -1) {
    os += lastIndex + " ";
    lastIndex = tx_val.indexOf('e',lastIndex + 1);
}
于 2013-10-04T16:08:53.550 回答
1

Others already provided the solution (second parameter of indexOf).

I'll just leave this line here

tx_val.replace(/e/g, function(str, i) {os = os + ' ' + i});
于 2013-10-04T16:36:06.373 回答
0

What if you try to split your string into an array of individuals characters, you parse it and store the matching indexes in another (output) array?

于 2013-10-04T16:12:52.333 回答