Reputation: 1925
I am trying to create a reverse function to the String type in javascript. My code is like
String.prototype.reverse = function () {
var s = "";
for(var i=this.length;i>=0;i--){
s+=this[i];
}
return s;
}
When I try to use it on for example like "test".reverse();
instead of giving "tset" it's giving "undefinedtset"
I am setting the variable like var s = ""
; inside the function, still undefined is coming. Why is it so?
Upvotes: 0
Views: 65
Reputation: 14941
The reason why your code isn't working has been answered by the others already, but if you want a shorter version of the reverse, you can do it like this:
String.prototype.reverse = function(){
return this.split('').reverse().join('');
}
console.log('Hello World'.reverse())
Upvotes: 2
Reputation: 152284
this.length
gives you 4
(4 letters in test
word) and you start iterating from 4
to 0
.
The problem is that nothing exists under 4
index (your letters are stored in 0-3
positions).
Try with:
for (var i = this.length - 1; i >= 0; i--) {
s += this[i];
}
Upvotes: 3
Reputation: 12880
You just need to change var i=this.length
to var i=this.length-1
, because an array starts at position 0 :
String.prototype.reverse = function () {
var s = "";
for(var i=this.length-1;i>=0;i--){
s+=this[i];
}
return s;
}
Upvotes: 4