JS - overwrite 'this' in function

I am trying to expand the prototype of an array:

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, up this = arr. It is bombing.

How to reassign a property of a thisprototype function? I want the hells to use the previous array configuration.

EDIT

Why am I doing this? I want it to behave like other array functions. For example, this works:

myArray.pop();

I do not need to do this:

myArray = myArray.pop();

OTHER IMAGES

I did this to solve this, but it seems silly:

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 will work, but in the example when rotating this array:

[[1, 1], [2, 2], [3, 3]]

I would get:

[[1, 2, 3], [1, 2, 3], ]

Look at this little empty third element? Yes, it caused me problems.

+4
source share
3 answers

this, , , , . - :

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.length = 0; //empty the array
  this.push.apply(this, arr); //push all of the elements from arr onto this
  return arr;
}
+8

this, this[i][j], this .

0

As @Meredith said, if you change this instead of a new array, you will get the expected result. the following test worked for me:

Array.prototype.rotate = function(){
    var a = this[0];
    this[0] = this[1];
    this[1] = a;
};

var test = [1,2];
test.rotate();
console.log(test); // [2,1]
0
source

Source: https://habr.com/ru/post/1539502/


All Articles