I want to create a mutable reverse method for a javascript string.
TL; DR:
Here is my attempt that did not work:
String.prototype.reverse = function() {
var reversed = {};
j = 0;
for (i = this.length - 1; i >= 0; i--)
{
reversed[j++] = this[i];
}
for (i in reversed)
{
this[i] = reversed[i];
}
};
...
str1 = "hello";
str1.reverse();
console.log(str1); //hello, not olleh
It doesn't change the string at all, as further evidenced by this small test:
String.prototype.makeFirstCharX = function() {
console.log(this[0]); //h
this[0] = 'x'; //no error
console.log(this[0]); //h ??
};
str1.makeFirstCharX();
console.log(str1); //hello, not xello
Is there anyway to overwrite values of this in a new protoype function for a native JS type? Why doesn't something like this[0]='x' give an error instead of just silently failing?
---This is what I tried on a custom JS object that did work as expected, which is what I based the above off of:
I can create a custom revsersible string that behaves similarly to a native string like this:
function MyString(str) {
//set string content and length
var l = 0;
for (i in str)
{
this[i] = str[i];
l++;
}
this.length = l;
}
MyString.prototype.toString = function()
{
var retVal = '';
for (i = 0; i < this.length; i++)
{
retVal += this[i];
}
return retVal;
};
MyString.prototype.reverse = function()
{
var reversed = {};
j = 0;
for (i = this.length - 1; i >= 0; i--)
{
reversed[j++] = this[i];
}
for (i in reversed)
{
this[i] = reversed[i];
}
};
So as expected:
str = new MyString('string');
console.log(str); // MyString { 0="s", 1="t", 2="r", more...}
console.log("" + str); //string
console.log(str.length); //6
str.reverse();
console.log(str); // MyString { 0="g", 1="n", 2="i", more...}
console.log("" + str); //gnirts
But if I try the same thing on a "real" javascript string, it does not work.