switch statement in for loop and if statement not completing

Posted by user2373912 on Stack Overflow See other posts from Stack Overflow or by user2373912
Published on 2014-06-03T21:19:15Z Indexed on 2014/06/03 21:24 UTC
Read the original article Hit count: 236

Filed under:
|

I'm trying to find out how many of each character are in a string.

I've searched around for a while and can't seem to figure out why my switch statement is stopping after the first case.

function charFreq(string){
    var splitUp = string.split("");
    console.log(splitUp);
    var a;
    var b;
    var c;
    var v;

    for (var i = 0; i<splitUp.length; i++){
        if (i<1){
            switch (splitUp[i]){
                case "a":
                 a = 1;
                break;
                case "b":
                 b = 1;
                break;
                case "c":
                 c = 1;
                break;
                case "v":
                 v = 1;
                break;
            }
        } else {
            switch (splitUp[i]){
                case "a":
                 a += 1;
                break;
                case "b":
                 b += 1;
                break;
                case "c":
                 c += 1;
                break;
                case "v":
                 v += 1;
                break;
            }
        } 
    } 
    console.log("There are " + a + " A's, " + b + " B's, " + c + " C's, and " + v + " V's.")
}

charFreq("aaabccbbavabac");

What am I doing wrong that would make the console read:

There are 6 A's, NaN B's, NaN C's, and NaN V's.

© Stack Overflow or respective owner

Related posts about for-loop

Related posts about switch-statement