Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript reverse string problem

  • This topic is empty.
Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #173642
    matthisco
    Participant

    Hi folks,

    I’m trying to reverse a string using a method of a function, I keep getting undefined in the console, can anyone please help?

    function MyString(string) {
        for (var i=0;i<string.length;i++) {
         this[i]=string.charAt(i);
       }
    
        this.reverseit = reverseit;
    
        function reverseit(string){
          for (var i = string.length - 1; i >= 0; i--){
             this[i]=string.charAt(i);
          };
       }
    }
    
    var s=new MyString('hello');
    
    console.log(s.reverseit('hello'));
    
    #173656
    clokey2k
    Participant

    It is difficult to see how you got to this code. What is this referring to in both of the for loops?

    For reversing you can use the code at http://stackoverflow.com/a/959004 but please read about the caveats of character encoding on the same page.

    You also might want to store the string used in your constructor to be reused in your reversed code.

    http://codepen.io/clokey2k/pen/doKGx

Viewing 2 posts - 1 through 2 (of 2 total)
  • The forum ‘JavaScript’ is closed to new topics and replies.