1

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.

4 Answers 4

3

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"
Sign up to request clarification or add additional context in comments.

Comments

1
var Reverse = (function() {
    return {
        reverse1: function(s) {
            var out = "";
            for (var i = s.length - 1, j = 0; i >= 0; i--, j++) out += s[i];
            return out;
        }
    };
})();
console.log(Reverse.reverse1("this is text"));

Comments

1

Use join method of array.

 return out.join('');

And change var out = new String(); to var out = [];

And Note:

You could do the below to reverse a string:

var ret = "this is text".split('').reverse().join('');

2 Comments

@enrmarc And change new String() to []
Thanks, I know reverse and split but I have to use only pure code: cocode.co/index.php?qa=67&qa_1=reversing-strings
1
var Reverse = (function() {

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.