I wrote a JS constructor which reverse a string variable:
function ReverseString(string) {
this.str = string;
var size = this.str.length;
this.reverse = function () {
for(size; size >= 0; --size) {
console.log(this.str[size]);
}
}
}
When I invoke a reverse method on a new string object("asd"
) it produces the following output:
undefined
d
s
a
Where this undefined
came from? Could you help me eliminate this ?
What about this easy step
it will reverse every word in its place
Here are three ways to reverse a string in javascript
Iterate through string in reverse order and push letters to array, then join the array
Use split, reverse, and join methods
Use ES6 arroe function and spread operator to copy as well as convert the string to array and then reverse and join
Call the three functions
Output
size
at beginning should belength -1
. You mix string reversing with string printing, but you can separate it as followsUser recusrsivity, easiest way to do it
The
length
problem is already explained. To solve it you could use:Another (more simple way) to reverse a string is to split it into an array, reverse that, and join again:
Applied to your method, something like this snippet:
At the beginning,
size
is going to be 3 (the length). There is nothing at index3
, henceundefined
. You need to initiate it atlength-1
.