Home > Software design >  Why isn't this function working like I expect it to? Trying to determine if a string has two re
Why isn't this function working like I expect it to? Trying to determine if a string has two re

Time:09-17

So here's what I have so far...

function doubleCheck(str){
    for (var i = 0; i <= str.length; i  ){
         var n = i   1;
        if (str[i] === str[n]){
        return "True";
        }
    }
}

I'm pretty new to Javascript. I googled around and I see there are better ways to solve this problem probably, but I can't figure out why this isn't working the way I think it should. If I pass a word without two consecutive letters like "train" this still returns true. Any help is appreciated.

CodePudding user response:

Your problem is that you did i <= str.length. Arrays in javascript start from 0.

In the case of 'train', it would go up to 5, which is undefined. It would compare undefined (array[5]) with undefined (array[6]), which is true.

  • Related