문제

I am trying to count how many times a letter appears in a string using indexOf(). Could you advise me on where I am going wrong in my code. Thanks!

var string = 'Lets find l as many times as we can. Love is natural, love you lots';

var myFunc = function (letter) {
    newString = 0;
    for (var i = 0; i < letter.length; i += 1) {
        if (string.indexOf('l')) {
            newString += 1;
        }
    }
    return newString;
}
도움이 되었습니까?

해결책

Instead of this

if (string.indexOf('l')) {
    newString += 1;
}

You can use charAt or even direct indexing to check each letter of a string.

Like this

if (letter[i] == 'l') {
    newString += 1;
}

or this

if (letter.charAt(i) == 'l') {
    newString += 1;
}

Here's a FIDDLE


Note that if you were to use indexOf you'd want to call it directly on the string in question, like this

letter.indexOf('l')

다른 팁

The other answer is perfectly good, but in case you really want a solution using indexOf (as the title of your question suggests), you need to provide it a second parameter, to tell it where to start looking for the next occurrence:

var myFunc = function (str) {
    var i = 0, c = 0;
    do {
        i = str.indexOf('l', i);
    } while (++i && ++c);
    return c;
}

Demonstration

But, if using indexOf is not a requirement, you can simplify this to:

var myFunc = function (str) {
    return str.split('l').length - 1;
}

A recursive method if you are insistent upon indexOf:

var myFunc = function (str, letter) {
    var count = 0,
        p = str.indexOf(letter);

    if (p > -1) {
        count += (1 + myFunc(str.slice(p + 1, str.length - 1), letter));
    }

    return count;
};

Fiddle

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top