I am trying to extend the Array prototype:
Array.prototype.rotate = function() {
var arr = [];
for (var i = 0; i < this[0].length; ++i) {
arr[i] = [];
for (var j = 0; j < this.length; ++j) {
arr[i].push(this[j][i])
}
}
this = arr;
return arr;
}
Totally dandy, until this = arr
. That bombs out.
How do I re-assign the this
property of a prototypal function? I want the hells to do with the previous array configuration.
EDIT
Why am I doing it this way? I want it to behave like other array functions. For example, this works:
myArray.pop();
I don't need to do this:
myArray = myArray.pop();
ANOTHER EDIT
I did this to solve it, but it seems stupid:
Array.prototype.rotate = function()
{
var arr = [];
var len = this[0].length;
for (var i = 0; i < len; ++i) {
arr[i] = [];
for (var j = 0; j < this.length; ++j) {
arr[i].push(this[j][i])
}
}
for (var i = 0; i < this.length; ++i) {
delete this[i];
}
for (var i = 0; i < arr.length; ++i) {
this[i] = arr[i];
}
return arr;
}
This would work, but, in an example, when rotating this array:
[[1, 1], [2, 2], [3, 3]]
I would get:
[[1, 2, 3], [1, 2, 3], ]
See that little blank third item? Yeah - that caused me problems.