Search code examples
javascriptstringify

JavaScript String Object to String


In node.js the next code

var Reverse = (function() {

    return {
        reverse1: function(s) {
            var out = new String();
            for (var i = s.length - 1, j = 0; i >= 0; i--, j++) {
                out[j] = s[i];
            }
            return out;
        }
    }
})();

console.log(Reverse.reverse1("this is text"));

prints

{ '0': 't',
  '1': 'x',
  '2': 'e',
  '3': 't',
  '4': ' ',
  '5': 's',
  '6': 'i',
  '7': ' ',
  '8': 's',
  '9': 'i',
  '10': 'h',
  '11': 't' 
}

But I want to print a string. I've tried return out.toString() but returns nothing.


Solution

  • Unless you have a real serious reason to need this done by array index, why not just concatenate onto it?

    out += s[i];
    

    Will print:

    // "txet si siht"