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 ?
I would use
reduceRight
:Now I have a handy routine I can also use to sum up sequences of numbers (in reverse order, but that doesn't matter).. For string:
In here you have get the size of the 'string' constructor parameter and you decrese the length of the given word('size' variable).
But the problem is when you input word 'asd', the length of that string is 3. So, when you access the index of str[3] should be undefined. Because,
So, your code should change,
So, output should be like this,